Entity structure code.

I have two objects that I want to associate with a 1: 1 ratio. The user is the main one, and UserActivation is dependent, but I have no idea how this works.

public class User { [Key] public Guid Id { get; set; } public string Name { get; set; } public string Lastname { get; set; } public string Username { get; set; } public virtual UserActivation UserActivation { get; set; } } public class UserActivation { [Key] public Guid Id { get; set; } public Guid UserId { get; set; } public bool Active { get; set; } public virtual User User { get; set; } } 

I tried to remove the keyword "virtual", tried to add ForeignKey ("UserId") or ForeignKey ("User"), I even tried to make [Key, ForeignKey ("User") and none of them helped me. I want to make a 1: 1 relationship using only dataannotations. Any help really appreciated. My two classes also have their own PCs.

+10
c # key entity-framework constraints
source share
1 answer

Foreign keys are not supported when trying 1: 1:

 public class User { [Key] public Guid Id { get; set; } public string Name { get; set; } public string Lastname { get; set; } public string Username { get; set; } public virtual UserActivation UserActivation { get; set; } } public class UserActivation { [Key] [ForeignKey("User")] public Guid Id { get; set; } public bool Active { get; set; } public virtual User User { get; set; } } 

Unable to determine the main end of the association between Model.PersonPhoto and Model.Person types. The main end of this association must be explicitly configured using the free interaction API or data annotations.

Julie Lerman discusses this in her book, First Code :

β€œThis problem is most easily resolved by using the ForeignKey annotation for the dependent class to determine that it contains the foreign key. When setting up a one-to-one relationship, the Entity Framework requires that the primary key of the dependent also be the foreign key. In our case, PersonPhoto is dependent , and its key PersonPhoto.PersonId must also be a foreign key. Add the PersonPhoto.PersonId property to the ForeignKey annotation, as shown in Example 4-21. Remember to specify the navigation property for the relationship when adding the ForeignKey annotation. "

+15
source share

All Articles