Convert iqueryable to IEnumerable

What is the problem with my code below. It does not return any elements, even if the corresponding entries are not present in db.if correctly, how can I convert 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

+8
linq entity-framework
source share
3 answers

In my opinion, if you are going to use linq, then hug him, get rid of this 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>(); } 
+6
source share

The reason you get null is because you are trying to convert an IQueryable based on 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 must remove the Select part for it to work.

If you want to select only Description and Title , create a named type with these two fields and return an IEnumerable this 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 }; } 
+4
source share

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; } 
+1
source share

All Articles