EF多对多关联

1、Book和Author表

    [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; }
    }
View Code
    [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; }
    }
View Code

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、执行

        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();
        }
View Code

 

posted @ 2022-04-02 13:53  江境纣州  阅读(34)  评论(0编辑  收藏  举报