gpt4 book ai didi

c# - Entity Framework Code First 一对一关系

转载 作者:可可西里 更新时间:2023-11-01 08:41:15 24 4
gpt4 key购买 nike

我有两个实体,我想建立一对一的关系。 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; }
}

我尝试删除“虚拟”关键字,尝试添加 ForeignKey("UserId") 或 ForeignKey("User"),我什至尝试制作 [Key, ForeignKey("User") 并且都没有他们帮助了我。我想仅使用数据注释建立 1:1 关系。非常感谢任何帮助。我的两个类(class)也都有自己的 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."

关于c# - Entity Framework Code First 一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com