How to query many-to-many releationship in EF Core

后端 未结 3 1217
我寻月下人不归
我寻月下人不归 2020-12-16 13:09

I\'m using .NET Core and EF Core for a web project. I\'m struggling how to query a many-to-many releationship. This is what my models look like:

public class         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 13:32

    EF Core won't load related properties automatically, so you'll need to explicitly do this, but something like the following should do the trick:

    var result = context.Begrip
        .Include(x => x.Categories)
        .ThenInclude(x => x.category);
    

    Note, intellisense doesn't always work on .ThenInclude at the moment, but the code should still compile even if it gets a red underline.

    If you're returning this to the view or an API, you'll likely want to map it to a DTO so you don't have to deal with .Categories[0].category.Name etc.

提交回复
热议问题