【问题标题】:Converting iQueryable to IEnumerable将 iQueryable 转换为 IEnumerable
【发布时间】:2012-04-11 01:05:53
【问题描述】:

我下面的代码有什么问题?即使数据库中存在匹配的记录,它也不会返回任何项目。如果错了,如何将我的IQueryable 转换为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;
}

【问题讨论】:

    标签: linq entity-framework c#-4.0


    【解决方案1】:

    在我看来,如果你打算使用 linq,那就拥抱它,摆脱那种深奥的符号:)

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

    【讨论】:

      【解决方案2】:

      您获得null 的原因是因为您试图将基于匿名类型IQueryable 转换为IEnumerable&lt;TimelineItem&gt;new { t.Description, t.Title } 创建匿名类型的实例有两个字段 - DescriptionTitle)您应该删除 Select 部分以使其工作。

      如果您只想选择 DescriptionTitle,请使用这两个字段创建一个 命名 类型,并返回该类型的 IEnumerable

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

      【讨论】:

      • 我不想选择所有项目。我只想选择描述和标题,这就是我使用 Select 的原因
      • @sureshcd10cvvc 如果您需要投影结果,请参阅我的编辑以了解如何做。
      【解决方案3】:

      使用自动映射器将IQueryable 转换为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;
                  }
      

      【讨论】:

        【解决方案4】:

        您将 IQueryable 转换为 IEnumerable 的业务用例是什么? IQueryable 将为您提供延迟或延迟的非缓存数据,而 IEnumerable 将为您提供即时或急切的缓存数据。但是,如果您在上下文级别关闭了延迟加载,您仍然可以获得即时数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-11
          • 2011-05-02
          • 2012-02-07
          • 1970-01-01
          相关资源
          最近更新 更多