EntityDataSource创建一个where子句

时间:2012-06-01 12:37:08

标签: c# entity-framework

这个课程:

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;}
}

我需要在一个ListBox中显示可用的角色,在其他ListBox中显示用户已经拥有且无法重复的角色。我在后面的代码中做了这个:

//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

它有效,但它很难维护,我喜欢使用EntityDataSource,但我不知道该怎么做。如果有人能帮助我,我将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:0)

使用EntityDataSource,您可以使用.Where属性指定过滤器。请注意,过滤器位于ESql中(有关ESql的更多详细信息:http://msdn.microsoft.com/en-us/library/bb399560)。 EntityDataSource与ObjectContext本身一起工作,而不与DbContext一起工作。您可以使用以下命令获取DbContext的ObjectContext实例:

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

要向EntityDataSource控件提供您自己的对象上下文,您需要处理OnContextCreating事件并将您从DbContext实例获取的上下文分配给EntityDataSourceContextCreatingEventArgs.Context属性。以下是详细信息:

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

以下是EntityDataSourceControl中如何使用.Where的示例: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.where.aspx 另一个关于一般过滤的问题: http://msdn.microsoft.com/en-us/library/cc488531

相关问题