Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c# - How to query many-to-many releationship in 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<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; } 
}

And my Database context:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...