EF -- Unable to determine the principal end of an association between the types

asp.net-mvc c# entity-framework entity-framework-6

Question

I'm having trouble working out what I am doing wrong here. I'm using asp.net Identity and I have created a new entity called Person. I updated the ApplicationUser Class to have a reference to the Person. I wanted to create a navigation property from Person to User. But when I execute the Update-Database I keep getting an error message

Unable to determine the principal end of an association between the types 'myapp.Models.ApplicationUser' and 'myapp.Models.DataModels.Person'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

public class Person 
{
    public Guid ID {get; set;}
    ...
    public virtual ApplicationUser user {get; set;}
}

public class ApplicationUser
{
    ...
    public Person person {get; set;}
}

In the code, I'm doing the following

ApplicationUser user = new ApplicationUser {...} 

Person person = new Person {....} 
user.person = person;

I'm also wondering whether I need to set anything for the Virtual property of Person such person.user = user;

I've tried to follow this Unable to determine the principal end of an association between the types by doing the following on the virtual property:

public class Person 
{
    public Guid ID {get; set;}
    ...
    [ForeignKey("ID")]        
    public virtual ApplicationUser user {get; set;}
}

Thanks

1
1
5/23/2017 12:31:59 PM

Popular Answer

In 1:1 relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal. Here you need to add [Required] attribute to one that is principal and remove [ForeignKey("ID")] from the model .

Also you have combined lazy loading (Virtual attribute) and eager loading features in your models.

4
1/25/2015 1:19:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow