У меня есть 2 таблицы Book
и Author
со многими отношениями.Реализация многих для многих для Entity Framework Core (v. 2.2.1) была взята здесь: https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many.
Я не могу понять, почему, когда я добавляю новую Книгу со связанными авторами, используя BookAuthor
таблица как дополнительная таблица для поддержки связи «многие ко многим», первичный ключ для сущности Author
не согласован. Я имею в виду, что свойство Id
имеет вид: 2, 4, 6, ..., а не 1, 2, 3, ...
Вот мой код:
public class Author
{
public int Id { get; set; }
public string FullName { get; set; }
public ICollection<BookAuthor> BookAuthors { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public ICollection<BookAuthor> BookAuthors { get; set; }
}
public class BookAuthor
{
public int BookId { get; set; }
public Book Book { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<BookAuthor> BookAuthors { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookAuthor>()
.HasKey(x => new {x.BookId, x.AuthorId});
modelBuilder.Entity<BookAuthor>()
.HasOne(pt => pt.Book)
.WithMany(p => p.BookAuthors)
.HasForeignKey(pt => pt.BookId);
modelBuilder.Entity<BookAuthor>()
.HasOne(pt => pt.Author)
.WithMany(t => t.BookAuthors)
.HasForeignKey(pt => pt.AuthorId);
}
}
А вот как я могу добавить новую книгу с авторами:
class Program
{
static void Main(string[] args)
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase("test")
.Options;
using (var context = new AppDbContext(options))
{
var book = new Book
{
Title = "Test Book",
BookAuthors = new List<BookAuthor>
{
new BookAuthor
{
Author = new Author
{
FullName = "Test name"
}
},
new BookAuthor
{
Author = new Author
{
FullName = "Author #2"
}
}
}
};
context.Books.Add(book);
context.SaveChanges();
}
}
}