EF多对多关联
1、Book和Author表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[Table("Book")] public partial class Book { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Book() { Author = new HashSet<Author>(); } public int Id { get; set; } public string Title { get; set; } public int Pages { get; set; } public string ISBN { get; set; } public string Publisher { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Author> Author { get; set; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[Table("Author")] public partial class Author { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Author() { Book = new HashSet<Book>(); } public int Id { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Book> Book { get; set; } }
2、外键约束,数据库有BookAuthor表,代码没有维护BookAuthor表。
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Author>() .HasMany(e => e.Book) .WithMany(e => e.Author) .Map(m => m.ToTable("BookAuthor").MapLeftKey("AuthorId").MapRightKey("BookId")); }
3、执行
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args) { KTStoreModel entity = new KTStoreModel(); entity.Database.Log = Console.WriteLine; IEnumerable<Author> authors = from author in entity.Author select author; foreach (Author author in authors) { Console.WriteLine($"{author.Name}著作"); foreach (Book book in author.Book) { Console.WriteLine(book.Title); } } Console.ReadLine(); }