如何在两个实体之间设置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
}
我试图这样做,但没有成功:
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
答案 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);
}