在Entity Framework Core中保存多對多關係

c# entity-framework-core many-to-many

例如,我有3個類,我用於多對多關係:

public class Library
{
    [Key]
    public string LibraryId { get; set; }
    public List<Library2Book> Library2Books { get; set; }
}

public class Book
{
   [Key]
   public string BookId { get; set; }
   public List<Library2Book> Library2Books { get; set; }
}

public class Library2Book
{
    public string BookId { get; set; }
    public Book Book { get; set; }

    public string LibraryId { get; set; }
    public Library Library { get; set; }
}

它們在ApplicationDbContext配置:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.Entity<CodeableConcept2Coding>().HasKey(k => new { k.LibraryId, k.BookId });
    builder.Entity<Library2Book>()
        .HasOne(x => x.Library)
        .WithMany(x => x.Library2Book)
        .HasForeignKey(x => x.LibraryId);
    builder.Entity<Library2Book>()
        .HasOne(x => x.Book)
        .WithMany(x => x.Library2Book)
        .HasForeignKey(x => x.BookId);
}

所以,我想在數據庫中添加一些Library2Books列表:

var library2Books = new List<Library2Books>(/*some sort of initialization*/);

我應該先添加什麼實體? BooksLibrary ?我怎麼能這樣做?

一般承認的答案

對於EF Core多對多關係來說,這是一個簡單而又非常基本的問題;我不知道為什麼沒有人在EF Core中為n..m編寫完整的例子。

我修改了你的代碼(主鍵為int ),我不喜歡主鍵中的字符串。只需複制/粘貼代碼,每個都應該正常工作。

我應該先添加什麼實體?書籍還是圖書館?我怎麼能這樣做?

順序並不重要,重要的是數據鏈接。必須正確鏈接數據,請參閱我的代碼行之間的註釋。

筆記:

  • 尚不支持沒有實體類來表示連接表的多對多關係!您必須有一個聯接表。

  • 多對多關係由兩個獨立的一對多關係組成。 = 2x 1:N

    class Program
    {
       public class Library
       {
         [Key]
         public int LibraryId { get; set; }
         public List<Library2Book> Library2Books { get; set; } = new    List<Library2Book>();
       }
    
       public class Book
       {
         [Key]
         public int BookId { get; set; }
         public List<Library2Book> Library2Books { get; set; } = new List<Library2Book>();
       }
    
       public class Library2Book
       {
         [Key]
         public int BookId { get; set; }
         public Book Book { get; set; }
    
         [Key]
         public int LibraryId { get; set; }
         public Library Library { get; set; }
       }
    
       public class MyDbContext : DbContext
       {
         public DbSet<Book> Books { get; set; }
    
         public DbSet<Library> Libraries { get; set; }
    
         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
         {
           optionsBuilder.UseSqlServer(@"Server=.\;Database=EFTutorial;integrated security=True;");
           base.OnConfiguring(optionsBuilder);
        }
    
         protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           modelBuilder.Entity<Library2Book>().HasKey(k => new { k.LibraryId, k.BookId });
    
           modelBuilder.Entity<Library2Book>()
               .HasOne(x => x.Book)
               .WithMany(x => x.Library2Books)
               .HasForeignKey(x => x.BookId);
    
           modelBuilder.Entity<Library2Book>()
              .HasOne(x => x.Library)
              .WithMany(x => x.Library2Books)
              .HasForeignKey(x => x.LibraryId);
    
           base.OnModelCreating(modelBuilder);
         }
       }
    
       static void Main(string[] args)
       {
         using (var myDb = new MyDbContext())
        {
          // Create Db
           myDb.Database.EnsureCreated();
    
           // I will add two books to one library
           var book1 = new Book();
           var book2 = new Book();
    
           // I create the library 
           var lib = new Library();
    
           // I create two Library2Book which I need them 
           // To map between the books and the library
           var b2lib1 = new Library2Book();
           var b2lib2 = new Library2Book();
    
           // Mapping the first book to the library.
           // Changed b2lib2.Library to b2lib1.Library
           b2lib1.Book = book1;
           b2lib1.Library = lib;
    
           // I map the second book to the library.
           b2lib2.Book = book2;
           b2lib2.Library = lib;
    
           // Linking the books (Library2Book table) to the library
           lib.Library2Books.Add(b2lib1);
           lib.Library2Books.Add(b2lib2);
    
           // Adding the data to the DbContext.
           myDb.Libraries.Add(lib);
    
           myDb.Books.Add(book1);
           myDb.Books.Add(book2);
    
           // Save the changes and everything should be working!
           myDb.SaveChanges();
         }
       }
    }
    

結果

Tables:   Books    |   Libraries      |    Library2Book  |
           1       |      1           |      1   |   1   |
           2       |      -           |      1   |   2   |

從問題的作者編輯

當你試圖插入很多實體時(我已經嘗試了大約300個實體),你已經添加了相同的密鑰錯誤。您應該將插入的集合拆分成小部分,例如100個實體就足夠了。

public async Task SaveEntities(IEnumerable<Library2Book> library2Books)
        {
                int i = 0;
                foreach (var library2Book in library2Books)
                {
                    _dbContext.Set<Library>().Add(codConc2Coding.Library);
                    _dbContext.Set<Book>().Add(codConc2Coding.Book);
                    _dbContext.Set<Library2Book>().Add(library2Book);
                    i++;
                    if (i == 99)
                    {
                        await _dbContext.SaveChangesAsync();
                        i = 0;
                    }
                }
                await _dbContext.SaveChangesAsync();
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow