【问题标题】:EntityDataSource create a where clauseEntityDataSource 创建 where 子句
【发布时间】:2012-06-01 12:37:08
【问题描述】:

有了这个类:

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 来制作它,但我不知道该怎么做。如果有人可以帮助我,我将不胜感激,谢谢。

【问题讨论】:

  • 你是先处理代码吗?

标签: c# entity-framework


【解决方案1】:

使用 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

【讨论】:

  • 嗨 Pawel,感谢 awnser,我终于得到了我需要的查询:var query = (from role in ctx.Role join userRole in ctx.User_Role on role.RoleId 等于 userRole.RoleId where userRole.UserId == userIdPassByUrl select new { role.RoleId, role.RoleName }).Distinct();如何将此查询设置为我的 EntityDataSource,我遇到了 Distinct 子句的问题。再次感谢。
  • 对于不同的,您需要使用 Select 属性,您应该能够放置 DISTINCT。以下是您如何使用 EntityDataSourceControl.Select 属性 msdn.microsoft.com/en-us/library/… ,这里是讨论 DISTINCT msdn.microsoft.com/en-us/library/bb399554 的 ESql SELECT 文档
猜你喜欢
  • 2014-10-04
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2012-05-18
  • 2011-01-31
  • 1970-01-01
相关资源
最近更新 更多