当从属实体只有外键而没有主键时,两个实体之间的C#EF关系0..1-1

时间:2019-03-01 07:49:18

标签: c# entity-framework entity-relationship

如何在两个实体之间设置EF关系,其中第一个(主)实体具有主键,而第二个(从属)实体则没有PK,只有第一个实体具有外键。

public class Dogovor
{
    public int Key { get;set; }
    public string Name { get;set; }
    public virtual DogovorStatus Status { get; set; }
}

public class DogovorStatus
{
    public int StatusKey { get; set; }

    //public int DogovorKey { get; set; }  // - no need, because this key is pointed in DogovorConfiguration        
}

DB tables

我试图这样做,但没有成功:

public class DogovorConfiguration : EntityTypeConfiguration<Dogovor>
{
    HasKey(v => v.Key);
    Property(v => v.Key)
        .IsRequired()
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
        .HasColumnName("DG_Key");
    Property(v => v.Name).
        .IsRequired()
        .HasColumnName("DG_Name");

    HasOptional(v => v.Status)
        .WithRequired()
        .Map(v => v.MapKey("ST_DGKey"));
}

public class DogovorStatusConfiguration : EntityTypeConfiguration<DogovorStatus> {

HasKey(v => v.StatusKey);  // not unique - logical error
Property(v => v.StatusKey)
    .IsRequired()
    .HasColumnName("ST_StatusKey");
}

我无法将PK添加到DogovorStatus。指出这类EF关系的正确方法是什么?

EF 6.0

1 个答案:

答案 0 :(得分:1)

也将导航属性添加到DogovorStatus类:

public class DogovorStatus
{
    public int StatusKey { get; set; }
    public virtual Dogovor Dogovor { get; set; }
}

然后调整配置:

public class DogovorStatusConfiguration : EntityTypeConfiguration<DogovorStatus> 
{
    HasKey(v => v.StatusKey);
}

public class DogovorConfiguration : EntityTypeConfiguration<Dogovor>
{
    HasKey(v => v.Key);
    Property(v => v.Key)
        .IsRequired()
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
        .HasColumnName("DG_Key");

    Property(v => v.Name)
        .IsRequired()
        .HasColumnName("DG_Name");

    HasOne(v => v.Status)
        .WithOne(s => s.Dogovor)
        .HasForeignKey<DogovorStatus>(s => s.StatusKey);
}

另请参阅参考Configuring One To One Relationships