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

问题描述 投票:0回答:1

如何使用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实体不同的实体的外键,我该怎么做?

foreign-keys entity-framework-core ef-fluent-api
1个回答
0
投票

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

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

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

我认为当您看到这一切时都会说得通。

© www.soinside.com 2019 - 2024. All rights reserved.