【问题标题】:How to specify the principal entity to which the foreign key refers using the Fluent API?如何使用 Fluent API 指定外键引用的主体实体?
【发布时间】:2019-11-30 11:47:47
【问题描述】:

如何使用 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 Core 是如何知道 AuthorFK 指的是 Author 实体。 IE。例如,如果我希望 AuthorFK 成为与 Author 实体不同的实体的外键,我该怎么做?

【问题讨论】:

    标签: foreign-keys entity-framework-core ef-fluent-api


    【解决方案1】:

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

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

    显示的方法 (modelBuilder.Entity&lt;Book&gt;().HasForeignKey) 不存在。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多