efcore多表查询出错_如何在EF Core中查询多对多关系

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 Categories { get; set; }

}

public class Category

{

public int ID { get; set; }

public string Name { get; set; }

public ICollection 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; }

}

And my Database context:

public class PBBContext : DbContext

{

public PBBContext (DbContextOptions options)

: base(options)

{

}

public DbSet Movie { get; set; }

public DbSet Begrip { get; set; }

public DbSet Category { get; set; }

public DbSet BegripCategory { get; set; }

protected override void OnModelCreating(ModelBuilder modelbuilder)

{

modelbuilder.Entity().HasKey(bc => new { bc.begripId, bc.categoryId });

modelbuilder.Entity().HasOne(b => b.begrip).WithMany(bg => bg.Categories).HasForeignKey(bc => bc.begripId);

modelbuilder.Entity().HasOne(c => c.category).WithMany(ca => ca.Begrippen).HasForeignKey(cc => cc.categoryId);

}

}

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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值