首页 > 解决方案 > 如何使用 Fluent API 指定外键引用的主体实体?

问题描述

如何使用 Fluent API 指定外键引用的主体实体?

我正在通过这里的教程学习 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 Core 是如何知道AuthorFK引用Author实体的。即,例如,如果我想AuthorFK成为与实体不同的Author实体的外键,我该怎么做?

标签: foreign-keysentity-framework-coreef-fluent-api

解决方案


令人惊讶的是,那里的教程是错误的。正确的方法是:

modelBuilder.Entity<Book>()
    .HasOne(e => e.Author)
    .WithMany()
    .HasForeignKey(e => e.AuthorFK);

显示的方法 ( modelBuilder.Entity<Book>().HasForeignKey) 不存在。

我想当你看到这一切时,一切都会变得有意义。


推荐阅读