简体   繁体   English

EntityDataSource创建一个where子句

[英]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. 我需要在一个ListBox中显示可用角色,而在其他ListBox中显示用户已经拥有且不能重复的角色。 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. 它可以工作,但是很难维护,我想用EntityDataSource来实现,但是我不知道该怎么做。 Please if anyone can help me I would be grateful, thanks. 请任何人能帮助我,我将不胜感激,谢谢。

With EntityDataSource you can use .Where property to specify filter. 通过EntityDataSource,您可以使用.Where属性指定过滤器。 Note that that the filter is in ESql (More details on ESql: http://msdn.microsoft.com/en-us/library/bb399560 ). 请注意,该过滤器位于ESql中(有关ESql的更多详细信息,请参见: http : //msdn.microsoft.com/zh-cn/library/bb399560 )。 EntityDataSource works natively with ObjectContext and not with DbContext. EntityDataSource与ObjectContext本身一起工作,而不与DbContext一起工作。 You can get an ObjectContext instance for your DbContext by using: 您可以使用以下方法获取DbContext的ObjectContext实例:

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. 要将自己的对象上下文提供给EntityDataSource控件,您需要处理OnContextCreating事件,并将从DbContext实例获取的上下文分配给EntityDataSourceContextCreatingEventArgs.Context属性。 Here are the details: 详细信息如下:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.contextcreating http://msdn.microsoft.com/zh-CN/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 下面是如何在EntityDataSourceControl使用。凡一个例子: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.where.aspx和另一个对一般过滤: http://msdn.microsoft.com/en-us/library/cc488531

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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