如何使用FluentAPI进行双向导航配置零或一到零或一个关系

时间:2014-07-22 16:28:32

标签: c# entity-framework ef-code-first

我正在尝试在实体框架的流畅API中创建一个0..1到0..1的关系。目标是配置从两端可导航的关系。

意思是:一个用户可能是医生,医生可能有也可能没有相关用户。

为导航目的建立双向关系会很有用。

此外,在Pysician上的foreignKey方面应该暴露ForeignKey属性(设置用户ID)。

这是我的模型和fluentAPI配置

public class Physician
{
    public long Id { get; set; }
    public string ProfessionalName { get; set; }

    public long? PhysicianUserID { get; set; }
    public virtual User PhysicianUser { get; set; }
}

public class User 
{

    public long Id { get; set; }
    public string Email { get; set; }

    public virtual Physician UserPhysician { get; set; }
}

        modelBuilder.Entity<Physician>()
            .HasOptional(A => A.PhysicianUser)
            .WithOptionalDependent(A => A.UserPhysician);

        modelBuilder.Entity<User>()
            .HasOptional(A => A.UserPhysician)
            .WithOptionalPrincipal(A => A.PhysicianUser);

问题是EF在Physician上创建了一个名为PhysicianUser_ID的属性(而不是使用我提供的属性)。我试图在医生实体上添加[ForeignKey()]声明但导致验证错误。

如何配置此类关系? (如果确实可能的话)

1 个答案:

答案 0 :(得分:-1)

你需要告诉Ef如何映射密钥

        modelBuilder.Entity<User>()
        .HasOptional(A => A.UserPhysician)
        .WithOptionalPrincipal(A => A.PhysicianUser)
        .Map(A => A.MapKey("PhysicianUserID"));