20

What is the problem with my code below? It's not returning any items even when matching records are present in the database. If it's 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;
}
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
Renny
  • 269
  • 1
  • 2
  • 10

3 Answers3

19

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>();
   }
Des Horsley
  • 1,858
  • 20
  • 43
Travis J
  • 81,153
  • 41
  • 202
  • 273
7

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 };
}
Nikola Bogdanović
  • 3,206
  • 1
  • 20
  • 28
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

Use auto mapper to convert IQueryable to IEnumerable

 StudentsModel IEmodel = new StudentsModel();//IEnumerable 
            try {
                var Queryablemodel = _tblStudents.GetQueryable().FirstOrDefault(x => x.CNIC == strCNIC && x.LoginPassword == strPassword);//IQueryable
               //conversion with Auto Mapper
                IEmodel = AutoMapper.Mapper.Map(Queryablemodel , IEmodel ); 
            }
            catch(Exception ex){
                throw ex;
            }
Muhammad Nasir
  • 2,126
  • 4
  • 35
  • 63