You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Entity Framework迁移报错:Nutrition实体需定义主键

解决Nutrition实体需定义主键的迁移错误

问题详情

我的数据库模型代码如下:

public class Recipe
{   
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public String imageUrl { get; set; }
    public Nutrition nutrition { get; set; }
}

public class Nutrition
{
    public int id { get; set; }
    public double calories { get; set; }
    public double caloriesDailyNormPercentage { get; set; }
    public double protein { get; set; }
    public double proteinDailyNormPercentage { get; set; }
}

执行EF Core迁移时弹出错误:

The entity type 'Nutrition' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'

我试过加[Key]、[ForeignKey()]属性,但都没解决问题。我的DataContext代码是:

public class DataContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseNpgsql("Host=localhost; Database=recepts; Username=postgres; Password=31029");

    public DbSet<Recipe> Recipes { get; set; }
    public DbSet<Nutrition> Nutritions { get; set; }
}

可行解决方案

方案1:修正主键命名(最省心)

EF Core的默认约定是识别**首字母大写的Id**作为实体主键,你Nutrition类里的主键是小写id,EF没自动识别到。把它改成大写开头:

public class Nutrition
{
    public int Id { get; set; } // 改成大写Id
    public double calories { get; set; }
    public double caloriesDailyNormPercentage { get; set; }
    public double protein { get; set; }
    public double proteinDailyNormPercentage { get; set; }
}

顺带把Recipe里的id也改成Id,保持项目命名规范统一。

方案2:手动配置主键(不改命名的情况)

如果不想调整命名,就在DataContext的OnModelCreating方法里手动指定主键:

public class DataContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseNpgsql("Host=localhost; Database=recepts; Username=postgres; Password=31029");

    public DbSet<Recipe> Recipes { get; set; }
    public DbSet<Nutrition> Nutritions { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 明确指定Nutrition的主键是小写id
        modelBuilder.Entity<Nutrition>().HasKey(n => n.id);
    }
}

额外提示:一对一关系配置

当前模型里Recipe和Nutrition是一对一关联,EF Core默认会把Nutrition的主键同时作为外键关联Recipe。如果需要让Nutrition能被多个Recipe引用(一对多),可以给Nutrition加外键字段:

public class Nutrition
{
    public int Id { get; set; }
    public int RecipeId { get; set; } // 新增外键
    public Recipe Recipe { get; set; } // 导航属性
    // 其他字段...
}

或者在OnModelCreating里显式配置关系:

modelBuilder.Entity<Recipe>()
    .HasOne(r => r.nutrition)
    .WithOne()
    .HasForeignKey<Nutrition>(n => n.RecipeId);

内容的提问来源于stack exchange,提问作者nikar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 15:07:12