在实体框架核心中保存多对多关系

本文关键字:关系 保存 实体 框架 核心 | 更新日期: 2023-09-27 18:02:00

例如,我有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*/);

我应该先添加哪个实体?Books还是Library ?我怎样才能进行储蓄呢?

在实体框架核心中保存多对多关系

这是EF Core多对多关系的一个简单而又非常基本的问题;我不知道为什么没有人在EF Core中为n..m写一个完整的例子。

我修改了你的代码(主键为int),我不喜欢主键中的字符串。只要复制/粘贴代码,每个都应该正常工作。

我应该先添加哪个实体?书还是图书馆?我怎样才能进行储蓄呢?

顺序不重要,这里重要的是数据链接。数据必须正确链接,参见我的代码行之间的注释。

指出:

  • 不支持没有实体类来表示连接表的多对多关系!你必须有一个连接表

  • 多对多关系由两个独立的一对多关系组成。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();
}