使用具有外键的EntityCollection初始化List <t> </t>

时间:2011-04-05 18:19:23

标签: linq frameworks collections entity

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

LINQ to Entities无法识别方法'System.Collections.Generic.List 1[Domain.Entities.Person] ToList[Person](System.Collections.Generic.IEnumerable 1 [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>();
            }
        }

1 个答案:

答案 0 :(得分:3)

你需要先执行并返回一个IEnumerable,然后使用linq到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();