Entity Framework 指定多重性

Entity Framework Specifying Multiplicity

我目前正在对以下模型使用 entity framework 代码优先(请参阅下文)。 1 Category 可以包含很多书,同样 1 rental 也可以包含很多书。

public class Book {
    public Guid Id {get; set;}
    public string Title {get; set;}

    public virtual BookCategory Category {get; set;}
}

public class BookCategory {
    public Guid Id {get; set;}
    public string Name {get; set;}

    public virtual ICollection<Book> Books {get; set;}
}

public class Rental {
    public Guid Id {get; set;}
    public DateTime DateRented {get; set;}

    public virtual ICollection<Book> Books {get; set;}
}

当我生成数据库时,我得到的是包含 BookCategory_Id 和 Rental_Id 的书 table。

图书Table

| Id | Title | BookCategory_Id | Rental_Id |

但是,这在我的上下文中不起作用,因为多次租借可能包含同一本书。有没有一种方法可以指定关系,这样 entity framework 将生成一个新的 table,其中包含如下内容:

Rental_Book Table

| Rental_Id | Book_Id |
|    aaa    |  book1  |
|    aaa    |  book2  |
|    bbb    |  book1  |

有什么帮助吗?

是的,您可以在 RentalBook 实体之间创建多对多关系。在 Book 实体中添加一个 Rentals 集合导航 属性:

public class Book {
    public Guid Id {get; set;}
    public string Title {get; set;}

    public virtual BookCategory Category {get; set;}
    public virtual ICollection<Rental> Rentals {get; set;}
}

然后,在上下文的 OnModelCreating 方法中添加此配置:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {

       modelBuilder.Entity<Book>()
                   .HasMany<Rental>(b => b.Rentals)
                   .WithMany(r => r.Books)
                   .Map(cs =>
                            {
                                cs.MapLeftKey("Book_Id");
                                cs.MapRightKey("Rental_Id");
                                cs.ToTable("Rental_Books");
                            });

  }

有关这种关系的更多信息,请查看此 link

您必须指定一本书可以租多本:

public class Book {
    public Guid Id {get; set;}
    public string Title {get; set;}

    public virtual BookCategory Category {get; set;}
    public virtual ICollection<Rental> Rentals {get; set;}
}

然后,是魔法无效,你要建立关系:

modelBuilder.Entity<Book>().HasMany(x => x.Rentals).WithMany(y => y.Books)