Initializing a List<T> using an EntityCollection that has a foreign key
I'm trying to initialize a List using results from the entity framework. Here is the error:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[Domain.Entities.Person] ToList[Person](System.Collections.Generic.IEnumerable
1[Domai开发者_如何学Pythonn.Entities.Person])' method, and this method cannot be translated into a store expression.
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>();
}
}
You need to execute first and return an IEnumerable then with linq to Objects create a list
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();
精彩评论