Fares Ayyad Fares Ayyad - 1 month ago 26
ASP.NET (C#) Question

Populate DropDownList Using EF

I trying to populate dropdownlist using EF, with

DataValueField= Terr_TerritoryID

and
DataTextField=Terr_Caption


In sql this is the command:

select Terr_Caption,Terr_TerritoryID
from Territories
where Terr_TerritoryID in (-1342177274,-1073741819,-805306364,-536870909,-268435454,268435456,1)


when I tried to write this sql using EF, like this:

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


when I execute nothing appeared in dropDownlist.

what is happening, can anyone help?

Answer

Your operator in the where should be OR and not AND. The same id can be both the first and the second and the third etc. values - but it can be x ory or 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
};

Even better is create a list of the values and use .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
};