foreign-keys - 如何使用 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
实体的外键,我该怎么做?
解决方案
令人惊讶的是,那里的教程是错误的。正确的方法是:
modelBuilder.Entity<Book>()
.HasOne(e => e.Author)
.WithMany()
.HasForeignKey(e => e.AuthorFK);
显示的方法 ( modelBuilder.Entity<Book>().HasForeignKey
) 不存在。
我想当你看到这一切时,一切都会变得有意义。
推荐阅读
- javascript - 使用 WordPress 的 MailChimp 订阅者弹出式迁移不起作用
- python-3.x - TensorFlow 1.9 是否支持 Python 3.7
- java - 使用 Jersey SSE 触发和输出事件
- c++ - BFS对节点的级别确定
- javascript - JavaScript - 如何检查输出是否具有相同的值
- javascript - 当屏幕尺寸小于 500 像素时,使用 javascript 垂直堆叠图像
- node.js - 使用文件元数据将节点请求流式传输到云
- php - 在相同的形式laravel中欺骗不同的方法
- python - robobrowser 'NoneType' 对象不支持项目分配
- laravel - 仅捕获 login.blade Laravel 中的无效凭据错误