简体   繁体   中英

EntityDataSource create a where clause

With this classes:

class User
{
int UserId{get;set;}
string UserName{get;set;}
}

class Role
{
int RoleId{get;set;}
string RoleName{get;set;}
}

class User_Role
{
int UserId{get;set;}
int RoleId{get;set;}
}

I need to show in one ListBox the Roles that are Availables and in other ListBox the Roles that the User already have and can not be repeated. I did this in the code behind:

//Initialize the ObjectContext
MyDbContext ctx = new MyDbContext();
int userId; //some value pass by url;
var listRolesIds = (ctx.Roles.Select(r => r.RoleId )).ToList();
var listRolesIdsAsigned = ctx.User_Role.Where(u => u.UserId == userId).Select(u => new {u.UserId}).ToList();

var listRolesIdsAvailables = listRoles.Except(listRolesAsigned);

//once i have the ids, code for Bind the ListBox with the availables roles

It works but its dificult to maintain and I like to make it with an EntityDataSource but I dont know how to do it. Please if anyone can help me I would be grateful, thanks.

With EntityDataSource you can use .Where property to specify filter. Note that that the filter is in ESql (More details on ESql: http://msdn.microsoft.com/en-us/library/bb399560 ). EntityDataSource works natively with ObjectContext and not with DbContext. You can get an ObjectContext instance for your DbContext by using:

var objectContext = ((IObjectContextAdapter)myDbContext).ObjectContext;

To supply your own object context to the EntityDataSource control you need to handle OnContextCreating event and assign the context you took from your DbContext instance to EntityDataSourceContextCreatingEventArgs.Context property. Here are the details:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.contextcreating

Here is an example of how to use .Where in EntityDataSourceControl: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.where.aspx and another one about filtering in general: http://msdn.microsoft.com/en-us/library/cc488531

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM