Renny
Renny

Reputation: 279

Converting iQueryable to IEnumerable

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;
}

Upvotes: 21

Views: 47998

Answers (3)

Travis J
Travis J

Reputation: 82337

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

Upvotes: 19

Muhammad Nasir
Muhammad Nasir

Reputation: 2204

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;
            }

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727037

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 };
}

Upvotes: 8

Related Questions