EF核心中的多对多关系

时间:2018-04-16 10:56:15

标签: .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>();
    }

}

Publicion House:

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,但我不知道如何创建它。我不知道如何获得包含所有publicHouses的书,本书包含

[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

}

1 个答案:

答案 0 :(得分:2)

对于实体框架核心,通常使用Include()后跟ThenInclude包含“儿童子女”实体

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

(另外,请注意,intellisense会诱使你相信这不是正确的语法,直到你完全写完它,有时你需要在它停止抱怨之前启动一个成功的构建)