Entity framework Code First 一对一关系

Entity framework Code First One-to-One relationship

我有两个实体想要建立 1:1 关系。 User 是主体,UserActivation 是从属的,但我不知道它是如何工作的。

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; }
}

我尝试删除 'virtual' 关键字,尝试添加 ForeignKey("UserId") 或 ForeignKey("User"),我什至尝试制作 [Key, ForeignKey ("User") 和 none 帮助了我。我只想使用数据注释建立 1:1 关系。非常感谢任何帮助。我的两个 类 都有自己的 PK。

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; }
}

无法确定类型“Model.PersonPhoto”和“Model.Person”之间关联的主体端。此关联的主体端必须使用流畅的关系 API 或数据注释进行显式配置。

Julie Lehrman 在 her Code First book 中对此进行了讨论:

"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."

这个 post 很旧,所以我想 post EF 6 解决方案

试试这个...

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
{
    [ForeignKey("User")]
    public Guid Id { get; set; }
    public Guid UserId { get; set; }
    public bool Active { get; set; }

    public virtual User User { get; set; }
}