开发者

EF LINQ Query - Many to Many

I need some help getting some data from an EF 4.1 query.

I have a Products table and a Categories table that have a Many-To-Many relationship on them.

I need to select a product by ID and include in it the categories it is associated with.

I came up with this:

    Public Function GetProductByID(ID As Integer) As Core.Entities.Product Implements Core.Interfaces.IProductService.GetProductByID
        Dim p = ProductRepository.Query.Single(Function(x) x.ID = ID)
        p.Categories = CategoryRepository.Query.Where(Function(x) x.Products.Any(Function(y) y.ID = ID)).ToList

        Return p

    End Function

I am sure there is a better way!开发者_如何学Go


Why not use Include() provided you have a property Categories on your Product entity? (C# syntax):

var p = ProductRepository.Include(x=> x.Categories)
                         .Single(x => x.ID == ID);

Also see Loading Related Objects

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜