简体   繁体   中英

Invalid ForeignKeyAttribute name with Entity Framework in code first approach

I have the following models

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; }
}

Here is my 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; }
}

Here is my Company class:

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

    public string Name { get; set; }
}

When I try to add a new migration I get the following error

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.

What am I doing wrong here?

Its just a typo, Company instead of Comapany

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

[ForeignKey("Comapny")] indicates that the property to use for the foreign key to the Company table should be Comapny .

The error is because you have not defined a Comapny property on the Company table.

Add the following to the Company table:

public int Comapny { get; set; }

Obviously it may be better to prefix it with Id just to show it is that type of field.

Or you could omit the [ForeignKey] attribute to let Entity Framework code first add one for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM