使用EF填充DropDownList

时间:2016-10-23 13:21:53

标签: c# asp.net entity-framework linq

我尝试使用EF填充下拉列表 DataValueField= Terr_TerritoryIDDataTextField=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中没有出现任何内容时。

发生了什么事,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您的运营商应位于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
};

答案 1 :(得分:0)

使用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();