.net - EF Core 中的多对多关系

标签 .net entity-framework asp.net-core entity-framework-core crud

我的 .NET Core 项目中有两个具有多对多关系的实体:

书:

public class Book
{
    [Key]
    public int BookId { get; set; }
    public string Name { get; set; }
    public string AuthorName { get; set; }
    public int YearOfPublishing { get; set; }
    public LibraryType Type { get; set; }

    public virtual ICollection<BookPublicHouse> PublicHouses { get; set; }

    public Book()
    {
        PublicHouses = new Collection<BookPublicHouse>();
    }

}

出版社:

public class PublicHouse
{
    [Key]
    public int PublicHouseId { get; set; }
    public string PublicHouseName { get; set; }
    public string Country { get; set; }
    public virtual ICollection<BookPublicHouse> Books { get; set; }

    public PublicHouse()
    {
        Books = new Collection<BookPublicHouse>();
    }
}

我创建连接表:

 public class BookPublicHouse
{
    public virtual Book Book { get; set; }
    public virtual PublicHouse PublicHouse { get; set; }
    public int BookId { get; set; }
    public int PublicHouseId { get; set; }
}

这是上下文类:

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

    public virtual DbSet<Book> Books { get; set; }
    public virtual DbSet<PublicHouse> PublicHouses { get; set; }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BookPublicHouse>()
            .HasKey(bp => new { bp.BookId, bp.PublicHouseId });

    }
}

接下来我需要使用 CRUD 操作创建 Api,但我不知道如何创建它。我不知道如何获取本书包含的所有公共(public)房屋,这本书包含

[Route("api/books")]
public class BookController : Controller
{
    private LibraryContext _dbContext;


    public BookController(LibraryContext context)
    {
        _dbContext = context;
        this.mapper = mapper;
    }
    //get()
    //get(id)
    //create()
    //update
    //delete

}

最佳答案

对于 Entity Framework 核心,通常使用 Include() 后跟 ThenInclude 来包含“子级的子级”实体

var book = _dbContext.Books
    .Include(b => b.PublicHouses)
    .ThenInclude(bph => bph.PublicHouse)
    .FirstOrDefault(b => b.BookId == 1);

(另外,请注意,智能感知会欺骗您相信这不是正确的语法,直到您完全编写它为止,有时您需要在它停止提示之前启动成功的构建)

关于.net - EF Core 中的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49855590/

相关文章:

.net - 如何在 VSTS 中构建 .net core 和完整的 .net 项目

.net - 如何在Windows中获取登录用户的全名?

.net - 函数名两边的方括号

c# - Entity Framework INNER JOIN 日期范围为 "BETWEEN"

c# - 从 .NET Core 运行 PowerShell

asp.net - 应如何使用 CompiledRazorAssemblyPart 加载 Razor View ?

c# - 我的字典大小正常吗?

c# - Xamarin.Forms 中的 Entity Framework 7

asp.net-core - .NET Core 1.1 - 获取 "Duplicate ' 内容'项目被包含在内”

c# - Entity Framework 代码优先迁移