【问题标题】:Populate DropDownList Using EF使用 EF 填充 DropDownList
【发布时间】:2016-10-23 13:21:53
【问题描述】:

我尝试使用 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 中没有出现任何内容。

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

【问题讨论】:

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


    【解决方案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
    };
    

    【讨论】:

    • 非常感谢,这解决了我的问题
    • 但为什么第二个溶胶更好?
    • @FaresAyyad - 欢迎您 :) 很高兴它解决了您的问题
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多