在Entity Framework 4.1 Code First中创建双向一对一关系

Inv*_*Dev 11 code-first relationships entity-framework-4.1

我想使用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; }

}
Run Code Online (Sandbox Code Playgroud)

我想在两个实体中同时拥有Navigation属性和Foreign Key.

这给了我错误.我可以在Fluent Mapping API中做些什么来使其工作?

Lad*_*nka 18

用这个:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这是在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; }
}
Run Code Online (Sandbox Code Playgroud)

在映射中,您将定义:

modelBuilder.Entity<User>
            .HasOptional(u => u.Profile)
            .WithMany()
            .HasForeignKey(u => u.ProfileId);
modelBuilder.Entity<Profile>
            .HasRequired(u => u.User)
            .WithMany()
            .HasForeignKey(u => u.UserId);
Run Code Online (Sandbox Code Playgroud)

现在您必须在数据库中定义唯一键 - 如果您使用的是代码,请首先使用自定义数据库初始化 r.请注意,仍然双向一对一是错误的概念,因为双方都要求唯一的FK,其中NULL仍然包含在唯一值中,因此一旦插入User之前Profile必须没有任何其他User没有Profile.这可能导致可序列化的交易.