How can I return a list of strings from a LINQ to Entities many-many relationship?
I have a view model that needs to encapsulate a couple of many-to-many relationships.
I have my LINQ to Entites query that returns the appropriate list, but can't figure out how to return a list of objects.
I have a Foo table, and a Bar table. Bar has a FK to Foo.ID, and a Description string. I want to create a FooViewModel that has Foo.ID, as well as list of all the Bar.Descriptions.
public class FooViewModel {
public int ID {get; set; }
public IEnumerable Descriptions { get; set; }
}
var all = from f in ctx.Foo.Include("Bar")
select new FooViewModel
{
ID = f.ID,
Descriptions = <insert magic here>
};
W开发者_如何学Gohat am I missing?
In Linq to Sql, Foo objects would have a property "Bar" (or "Bars" if it's one-to-many), so it would be just:
var all = from f in ctx.Foo
select new FooViewModel
{
ID = f.ID,
Descriptions = f.Bars;
};
I'm told it works the same way in Linq-to-Entity, with the proviso that while that property is automatically create in L2S, there's some explicit task you must do manually to have L2e create it.
精彩评论