如何使用Fluent API指定外键所引用的主体?
我正在通过here上的教程学习EF Core。
我遇到以下示例:
public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorFK { get; set; }
public Author Author { get; set; }
}
public class SampleContext : DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasForeignKey(p => p.AuthorFK);
}
}
而且我不明白EF核心如何知道AuthorFK
指的是Author
实体。即例如,如果我希望AuthorFK
是与Author
实体不同的实体的外键,我该怎么做?
令人惊讶的是,该教程在这里是错误的。正确的方法是:
modelBuilder.Entity<Book>()
.HasOne(e => e.Author)
.WithMany()
.HasForeignKey(e => e.AuthorFK);
显示的方法(modelBuilder.Entity<Book>().HasForeignKey
)不存在。
我认为当您看到这一切时都会说得通。