0

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?

1
  • 1
    Are you sure is "Comapny" and not "Company"? Commented Jul 10, 2016 at 20:58

2 Answers 2

1

Its just a typo, Company instead of Comapany

[ForeignKey("Company")]
    public int CompanyId { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

[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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.