Iqueryable to IEnumerable conversion

c#-4.0 entity-framework linq

Question

What is the problem with my code below.Its not returning any items even when matching records are present in db .if wrong how can I convert my IQueryable to IEnumerable ?

public IEnumerable<TimelineItem> TimeLineItems { get; set; }
        public IEnumerable<TimelineItem> GetTimeLineItems(int SelectedPID)
        {
            TimeLineItems = (from t in db.TimelineItems
                             where t.ProductID == SelectedPID
                             select new { t.Description, t.Title })as IEnumerable<TimelineItem>;
            return TimeLineItems;
        }

Thanks

1
13
4/11/2012 1:05:53 AM

Accepted Answer

In my opinion, if you are going to use linq then embrace it, get rid of that esoteric notation :)

   public IEnumerable<TimelineItem> GetTimeLineItems(int SelectedPID)
   {
      return db.TimelineItems.Where(tl => tl.ProductID == SelectedPID)
        .Select( tl => new TimelineItem {
            Description = tl.Description,
            Title = tl.Title })
        .AsEnumerable<TimelineItem>();
   }
10
12/9/2015 12:39:06 AM

Popular Answer

The reason you are getting null is because you are trying to convert an IQueryable based on an an anonymous type to IEnumerable<TimelineItem> (new { t.Description, t.Title } creates an instance of an anonymous type with two fields - Description and Title) You should remove the Select part to make it work.

If you would like to select only Description and Title, create a named type with these two fields, and return an IEnumerable of that type:

public class TitleDescr {
    public string Title {get;set;}
    public string Description {get;set;}
}

public IEnumerable<TitleDescr> GetTimeLineItems(int SelectedPID)
{
    return from t in db.TimelineItems
                     where t.ProductID == SelectedPID
                     select new TitleDescr { t.Description, t.Title };
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow