【问题标题】:Initializing a List<T> using an EntityCollection that has a foreign key使用具有外键的 EntityCollection 初始化 List<T>
【发布时间】:2011-04-05 18:19:22
【问题描述】:

我正在尝试使用实体框架的结果初始化一个列表。这是错误:

LINQ to Entities 无法识别方法 'System.Collections.Generic.List1[Domain.Entities.Person] ToList[Person](System.Collections.Generic.IEnumerable1[Domain.Entities.Person])' 方法,并且此方法无法转换为存储表达式。

 public List<Domain.Entities.Event> Events
        {
            get
            {
                Entities context = new Entities(connectionString);

                return (from c in context.Events.Include("EventPeople")
                        select new Domain.Entities.Event()
                        {
                            ID = c.ID,
                            Title = c.Title,
                            Description = c.Description,
                            Date = c.Date,
                            People = (from ep in c.EventPeople
                                     select new Domain.Entities.Person()
                                     {
                                         ID = ep.ID,
                                         Name = ep.Name
                                     }).ToList<Person>()
                        }).ToList<Domain.Entities.Event>();
            }
        }

【问题讨论】:

    标签: linq frameworks collections entity


    【解决方案1】:

    您需要先执行并返回一个 IEnumerable,然后使用 linq to Objects 创建一个列表

    var events = (from c in context.Events.Include("EventPeople")
                        select new
                        {
                            ID = c.ID,
                            Title = c.Title,
                            Description = c.Description,
                            Date = c.Date,
                            People = (from ep in c.EventPeople
                                     select new Domain.Entities.Person()
                                     {
                                         ID = ep.ID,
                                         Name = ep.Name
                                     })
                        }).ToList();
    return events.Select(e => new  Domain.Entities.Event()
                        {
                            ID = e.ID,
                            Title = e.Title,
                            Description = e.Description,
                            Date = e.Date,
                            People = e.People.ToList()
                        }).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      相关资源
      最近更新 更多