[英]Populate DropDownList Using EF
我試圖使用EF填充dropdownlist,其中DataValueField= Terr_TerritoryID
和DataTextField=Terr_Caption
在sql中,這是命令:
select Terr_Caption,Terr_TerritoryID
from Territories
where Terr_TerritoryID in (-1342177274,-1073741819,-805306364,-536870909,-268435454,268435456,1)
當我嘗試使用EF編寫此sql時,如下所示:
var tc = (from t in db.Territories
where t.Terr_TerritoryID == -1342177274 &&
t.Terr_TerritoryID == -1073741819 &&
t.Terr_TerritoryID == -805306364 &&
t.Terr_TerritoryID == -805306364
select new
{
terCapt = t.Terr_Caption,
terID = t.Terr_TerritoryID
});
ddlTer.DataSource = tc.ToList();
ddlTer.DataValueField = "terID";
ddlTer.DataTextField = "terCapt";
ddlTer.DataBind();
當我執行時,dropDownlist中什么也沒有出現。
發生了什么事,有人可以幫忙嗎?
您在where中的運算符應為OR
而不是AND
。 相同的ID可以是第一個,第二個和第三個等值-但可以是x ory或z。
from t in db.Territories
where t.Terr_TerritoryID == -1342177274 ||
t.Terr_TerritoryID == -1073741819 ||
t.Terr_TerritoryID == -805306364 ||
t.Terr_TerritoryID == -805306364
select new
{
terCapt = t.Terr_Caption,
terID = t.Terr_TerritoryID
};
更妙的是創建值列表,並使用.Contains
:
var ids = new List<int> { -1342177274, -1073741819, -805306364, -805306364 };
from t in db.Territories
where ids.Contains(t.Terr_TerritoryID)
select new
{
terCapt = t.Terr_Caption,
terID = t.Terr_TerritoryID
};
與Lambda
var ids = new List<int> { -1342177274, -1073741819, -805306364, -805306364 };
var tc= db.Territories.where(x=>ids.Contains(x.Terr_TerritoryID))
.select new
{
terCapt = t.Terr_Caption,
terID = t.Terr_TerritoryID
};
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.