[SOLVED] Unable to determine the principal end of an association

Recently while using FluentAPI in ASP.NET MVC project with Entity Framework I encountered below error

Unable to determine the principal end of an association between the types ‘MyApplication.User’ and ‘ MyApplication .Address’. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

This error occurs when you have one to zero or one to zero-or-one relationship between your objects. In my case I was using a User model which has one to zero-or-one relationship with Address class.

This issue can be solved by using below mapping in FluentAPI

modelBuilder.Entity<User>.HasOptional(u => u.Address).WithRequired(a => a.User);

It tells that for every Address object one User object is required but for every User object Address is optional (zero-or-one).

You can do the same thing using data annotation also:

public class Address
{
    [Key, ForeignKey("User")]
    public int UserId { get; set; }
    public User User { get; set; }
}