开发者

linq problem with distinct function

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开发者_C百科? Thank you in advance.


You're already selecting Source in the LINQ query, which is how the result is an IQueryable<string>. You're then also specifying Source as the property to find in each string in the databinding. Just take out the statements changing the DataTextField and DataValueField properties in databinding.

Alterantively you could remove the projection to p.Source from your query and return an IQueryable<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 GetAllSources query. I'd just write this as:

public IQueryable<string> GetAllSource()
{
    PromotionDataContext dc = new PromotionDataContext(_connString);
    return dc.Promotions
             .Select(p => p.Source)
             .Distinct();
}

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.


You're trying to bind strings, not Promotion objects... and strings do not have Source property/field


Your method returns a set of strings, not a set of objects with properties.

If you really want to bind to a property name, you need a set of objects with properties (eg, by writing select new { Source = Source })

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜