Entity framework Code First One-to-One relationshi

2019-03-26 17:52发布

问题:

I have two entities which I want to be connected 1:1 relationship. User is principal and UserActivation is dependent, but I have no idea how that 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 have tried to remove 'virtual' keyword, have tried to add ForeignKey("UserId") or ForeignKey("User"), I've even tried to make [Key, ForeignKey("User") and none of them helped me. I want to make 1:1 relationship using only dataannotations. Any help is really appreciated. Also my both classes has their own PKs.

回答1:

Foreign keys are not supported for 1:1 try:

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 principal end of an association between the types ‘Model.PersonPhoto’ and ‘Model.Person’. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

This problem is most easily solved by using a ForeignKey annotation on the dependent class to identify that it contains the foreign key. When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key. In our case PersonPhoto is the dependent and its key, PersonPhoto.PersonId, should also be the foreign key. Go ahead and add in the ForeignKey annotation to the PersonPhoto.PersonId property, as shown in Example 4-21. Remember to specify the navigation property for the relationship when adding the ForeignKey annotation.