我正在尝试在 EntityFrameworkCore 中初始化我的数据库上的外键,并遵循本指南https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs= Fluent-api 我相信我应该只需使用 .HasForeignKey 方法即可。但是我收到以下错误
“KeyBuilder”不包含“HasForeignKey”的定义,并且找不到接受“KeyBuilder”类型的第一个参数的可访问扩展方法“HasForeignKey”(您是否缺少 using 指令或程序集引用?)
这是我的代码
using Microsoft.EntityFrameworkCore;
using TemplateApi.Models;
namespace TemplateApi
{
public class DatabaseContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>()
.HasKey(b => b.ID);
modelBuilder.Entity<Role>()
.HasKey(b => b.Id)
.HasForeignKey(b => b.Department_Id);
}
}
}
Run Code Online (Sandbox Code Playgroud)
部门:
using System.Collections.Generic;
namespace TemplateApi.Models
{
public class Department
{
public int ID { get; set; }
public string Name { …Run Code Online (Sandbox Code Playgroud)