I am trying to bind distinct records to a dropdownlist. After I added distinct function of the linq query, it said “DataBinding: ‘System.String’ does not contain a property with the name ‘Source’. ” I can guarantee that that column name is ‘Source’. Is that name lost when doing distinct search?
My backend code:
public IQueryable<string> GetAllSource()
{
PromotionDataContext dc = new PromotionDataContext(_connString);
var query = (from p in dc.Promotions
select p.Source).Distinct();
return query;
}
Frontend code:
PromotionDAL dal = new PromotionDAL();
ddl_Source.DataSource = dal.GetAllSource();
ddl_Source.DataTextField = "Source";
ddl_Source.DataValueField = "Source";
ddl_Source.DataBind();
Any one has a solution? Thank you in advance.
You’re already selecting
Sourcein the LINQ query, which is how the result is anIQueryable<string>. You’re then also specifyingSourceas the property to find in each string in the databinding. Just take out the statements changing theDataTextFieldandDataValueFieldproperties in databinding.Alterantively you could remove the projection to
p.Sourcefrom your query and return anIQueryable<Promotion>– but then you would get distinct promotions rather than distinct sources.One other quick note – using query syntax isn’t really helping you in your
GetAllSourcesquery. I’d just write this as:Query expressions are great for complicated queries, but when you’ve just got a single select or a where clause and a trivial projection, using the dot notation is simpler IMO.