EntityTypeBuilder无HasForeignKey定义,ASP.NET Web API问题求助
我尝试在ASP.NET Web API的Context.cs中使用.HasForeignKey方法指定外键,参考示例代码:
modelBuilder.Entity<Book>() .HasForeignKey(p => p.AuthorFK);
但程序无法识别HasForeignKey,抛出错误CS1061:
'EntityTypeBuilder' does not contain a definition for 'HasForeignKey' and no accessible extension method 'HasForeignKey' accepting a first argument of type 'EntityTypeBuilder' could be found (are you missing a using directive or an assembly reference?)
我的Context代码如下:
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.SqlServer; namespace RevPiControlAPI.Models { public class ThisContext : DbContext { public ThisContext(DbContextOptions<ThisContext> options) : base(options) { } public DbSet<RevPis> RevPis { get; set; } public DbSet<RevPiModels> RevPiModels { get; set; } public DbSet<Modules> Modules { get; set; } public DbSet<ModuleModels> ModuleModels { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<RevPis>().HasForeignKey(i => i.RevPiModelId); } } }
使用的NuGet包版本:
- Microsoft.VisualStudio.Web.CodeGeneration.Design {7.0.9}
- Microsoft.AspNetCore.OpenApi {7.0.13}
- Microsoft.EntityFrameworkCore {7.0.13}
- Microsoft.EntityFrameworkCore.SqlServer {7.0.13}
- Microsoft.EntityFrameworkCore.InMemory {7.0.13}
- Swashbuckle.AspNetCore {6.5.0}
- Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore {7.0.13}
- Microsoft.EntityFrameworkCore.Tools {7.0.12}
错误核心是HasForeignKey不能直接在EntityTypeBuilder<T>上调用,它是关系配置阶段的方法,必须先通过HasOne或HasMany明确实体间的关联关系,才能调用该方法指定外键。
针对你的场景,假设RevPis与RevPiModels是一对多关系(一个RevPiModels对应多个RevPis),正确写法如下:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<RevPis>() .HasOne<RevPiModels>() // 声明RevPis属于一个RevPiModels .WithMany() // 声明RevPiModels对应多个RevPis(一对一关系则用WithOne) .HasForeignKey(i => i.RevPiModelId); // 指定外键字段 }
如果实体类定义了导航属性(比如RevPis包含RevPiModel属性,RevPiModels包含RevPis集合属性),可以用更明确的写法:
// 实体类示例定义: // public class RevPis { public int RevPiModelId { get; set; } public RevPiModels RevPiModel { get; set; } } // public class RevPiModels { public int Id { get; set; } public ICollection<RevPis> RevPis { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<RevPis>() .HasOne(r => r.RevPiModel) .WithMany(m => m.RevPis) .HasForeignKey(r => r.RevPiModelId); }
另外,你的代码已经包含Microsoft.EntityFrameworkCore命名空间(HasForeignKey的扩展方法所在命名空间),所以无需额外添加using指令,核心问题是调用顺序错误。
内容的提问来源于stack exchange,提问作者jake704

