I have a project built on the top of the ASP.NET MVC 5 framework. I am using Entity Framework 6.2 to access data from my database.
I have the following two models
public class Entity<T> where T : struct
{
[Key]
public T Id { get; set; }
}
public class User : Entity<int>
{
public string FirstName { get; set; }
public int CategoryId { get; set; }
// more properties removed for the sake of simplicity
public virtual Category Category { get; set; }
}
public class Category : Entity<int>
{
public string Name { get; set; }
}
Here is how I am accessing the user from the database-context.
User user = await DbContext.Users.FirstAsync(10);
However, I am getting the following unexpected exception.
Unable to determine the principal end of an association between the types 'Category' and 'User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
I tried adding [ForeignKey] attribute to the Category property but that did not work either:
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
I also tried adding InverseProperty attribute
[ForeignKey("CategoryId")]
[InverseProperty("Id")]
public virtual Category Category { get; set; }
but the inverse-property annotation throws the following error:
The property 'Id' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.
What could be causing this issue? How can I fix it?
I couldn't repro (EF 6.4):
outputs