在代码优先方法中使用 Entity Framework 的无效 ForeignKeyAttribute 名称

Invalid ForeignKeyAttribute name with Entity Framework in code first approach

我有以下型号

public class Team
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

    [ForeignKey("User")]
    public int ManagerId { get; set; }

    public virtual User User { get; set; }
}

这是我的 User class:

public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    [ForeignKey("Comapny")]
    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
}

这是我的 Company class:

public class Company
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }
}

当我尝试添加新迁移时出现以下错误

The ForeignKeyAttribute on property 'CompanyId' on type 'ReportsEngine.Areas.Test.Models.User' is not valid. The navigation property 'Comapny' was not found on the dependent type 'ReportsEngine.Areas.Test.Models.User'. The Name value should be a valid navigation property name.

我做错了什么?

只是打错了,是Company而不是Company

[ForeignKey("Company")]
    public int CompanyId { get; set; }

[ForeignKey("Comapny")] 表示 属性 用于 Company table 的外键应该是 Comapny.

错误是因为你没有在Companytable.

上定义Comapny属性

将以下内容添加到 Company table:

public int Comapny { get; set; }

显然,在它前面加上 Id 可能更好,只是为了表明它是那种类型的字段。

或者您可以省略 [ForeignKey] 属性,让 Entity Framework 代码先为您添加一个。