如何在EF Core中查询多对多关系 [英] How to query many-to-many releationship in EF Core

查看:1066
本文介绍了如何在EF Core中查询多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将.NET Core和EF Core用于Web项目.我在努力查询多对多关系.这是我的模型的样子:

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 Begrip
{
    public int ID { get; set; }
    public string Name { get; set; } 
    public string Desc { get; set; }
    [Url]
    public string URL { get; set; } 
    public ICollection<BegripCategory> Categories { get; set; } 
}

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; } 
    public ICollection<BegripCategory> Begrippen { get; set; }
}

public class BegripCategory
{
    public int begripId { get; set; }
    public Begrip begrip { get; set; } 
    public int categoryId { get; set; }
    public Category category { get; set; } 
}

和我的数据库上下文:

public class PBBContext : DbContext
{
    public PBBContext (DbContextOptions<PBBContext> options)
        : base(options)
    {
    }

    public DbSet<PBB.Models.Movie> Movie { get; set; }
    public DbSet<PBB.Models.Begrip> Begrip { get; set; } 
    public DbSet<PBB.Models.Category> Category { get; set; } 
    public DbSet<PBB.Models.BegripCategory> BegripCategory { get; set; }

    protected override void OnModelCreating(ModelBuilder modelbuilder)
    {
        modelbuilder.Entity<BegripCategory>().HasKey(bc => new { bc.begripId, bc.categoryId });

        modelbuilder.Entity<BegripCategory>().HasOne(b => b.begrip).WithMany(bg => bg.Categories).HasForeignKey(bc => bc.begripId);
        modelbuilder.Entity<BegripCategory>().HasOne(c => c.category).WithMany(ca => ca.Begrippen).HasForeignKey(cc => cc.categoryId);
    }
}

我想做的是在JSON结果中返回所有"Begrippen"以及所有相应的类别",但是,我不知道如何获取它们的类别"列表.

What im trying to do is to return all the "Begrippen" in a JSON result with all the corresponding "Categories", however, I can't figure out how to get the list of "Categories" for them.

有什么想法吗?提前致谢.

Any ideas? Thanks in advance.

推荐答案

EF Core不会自动加载相关属性,因此您需要显式执行此操作,但以下方法可以解决问题:

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);

请注意,目前intellisense并不总是在.ThenInclude上运行,但是即使下划线为红色,代码仍应编译.

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

如果要将其返回到视图或API,则可能需要将其映射到DTO,这样就不必处理.Categories[0].category.Name等.

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.

这篇关于如何在EF Core中查询多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆