簡體   English   中英

EntityDataSource創建一個where子句

[英]EntityDataSource create a where clause

使用此類:

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來實現,但是我不知道該怎么做。 請任何人能幫助我,我將不勝感激,謝謝。

通過EntityDataSource,您可以使用.Where屬性指定過濾器。 請注意,該過濾器位於ESql中(有關ESql的更多詳細信息,請參見: http : //msdn.microsoft.com/zh-cn/library/bb399560 )。 EntityDataSource與ObjectContext本身一起工作,而不與DbContext一起工作。 您可以使用以下方法獲取DbContext的ObjectContext實例:

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

要將自己的對象上下文提供給EntityDataSource控件,您需要處理OnContextCreating事件,並將從DbContext實例獲取的上下文分配給EntityDataSourceContextCreatingEventArgs.Context屬性。 詳細信息如下:

http://msdn.microsoft.com/zh-CN/library/system.web.ui.webcontrols.entitydatasource.contextcreating

下面是如何在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