我想使用 EF Code First 在两个实体之间创建双向一对一关系。我在使用以下代码时遇到问题。你觉得我应该怎么做?
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public int ProfileID { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int UserID { get; set; }
public User User { get; set; }
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
}
我想在两个实体中都拥有导航属性和外键。
这给了我错误。我可以在 Fluent Mapping API 中做什么来完成这项工作?
用这个:
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
[Key, ForeignKey("User")]
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public User User { get; set; }
}
这是在 EF 中建立一对一关系的唯一有效方法 - 依赖实体的 PK 也必须是主体实体的 FK。 EF 中不存在双向一对一关系,因为它无法在 EF 中工作。
人们有时克服这个问题的方法是两个一对多关系,其中主体没有依赖实体的导航集合+数据库中手动定义的唯一键。需要手动映射:
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
// one side MUST be nullable otherwise you have bidirectional constraint where each
// entity demands other side to be inserted first = not possible
public int? ProfileId { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
在映射中您将定义:
modelBuilder.Entity<User>
.HasOptional(u => u.Profile)
.WithMany()
.HasForeignKey(u => u.ProfileId);
modelBuilder.Entity<Profile>
.HasRequired(u => u.User)
.WithMany()
.HasForeignKey(u => u.UserId);
现在您必须在数据库中定义唯一键 - 如果您使用代码首先使用自定义数据库初始化河请注意,双向一对一仍然是错误的概念,因为双方都需要唯一的 FK,其中 NULL 仍然包含在唯一值中,因此一旦插入User
before Profile
一定没有其他的User
没有Profile
。这可能会导致可序列化事务。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)