3

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

Community
  • 1
  • 1
user3836415
  • 952
  • 1
  • 10
  • 25

1 Answers1

6

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.

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
  • Hi Amir, which one should I place the required attribute - should it be in the ApplicationUser.Person or Person.User ? I'm assuming it should be in ApplicationUser.Person but i tried it on Person.User and I'm able to execute Update-Database. But I would have thought that the ApplicationUser entity would be getting created first. – user3836415 Jan 25 '15 at 01:52
  • @user3836415 Which one is dependant? Add `[Required]` attribute for its navigation property. – Amirhossein Mehrvarzi Jan 25 '15 at 02:18
  • I've tried to add the [required] annotation to each one and compiled it each time and I'm getting the same result. – user3836415 Jan 25 '15 at 04:28
  • I also find that [Required] attr must be added to both the Id property and the reference property – dlchambers Aug 17 '15 at 14:09