我有两个具有一对一关系的实体,其中目标实体的主键和外键相同。这是两个实体及其流畅的映射。
public class Register
{
public int Id { get; set; }
public string Number { get; set; }
// N.B: Here I can't have this virtual property for my project dependencies.
//public virtual CustomerDisplay CustomerDisplay { get; set; }
}
public class CustomerDisplay
{
public int RegisterId { get; set; }
public double ReceiptViewPercent { get; set; }
public virtual Register Register { get; set; }
}
public class RegisterConfiguration : EntityConfig<Register>
{
public RegisterConfiguration(bool useIdentity, bool sqlServerCe)
: base(sqlServerCe)
{
this.HasKey(t => t.Id);
if (!useIdentity)
{
Property(d => d.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
this.Property(t => t.Number).IsRequired().HasMaxLength(20);
}
}
public class CustomerDisplayConfiguration: EntityConfig<CustomerDisplay>
{
public CustomerDisplayConfiguration(bool sqlServerCe)
: base(sqlServerCe)
{
this.HasKey(t => t.RegisterId);
this.HasRequired(t => t.Register).WithMany().HasForeignKey(d => d.RegisterId).WillCascadeOnDelete(false);
}
}
我收到以下错误:
我在 stackoverflow 中看到了很多相关问题,但没有找到我的解决方案。这个最符合我的问题:
How to declare one to one relationship ...
谁能告诉我如何解决这个问题。谢谢
最佳答案
再次添加 CustomerDisplay
导航属性:
public class Register
{
public int Id { get; set; }
public string Number { get; set; }
public virtual CustomerDisplay CustomerDisplay { get; set; }
}
并按照我显示的方式配置关系:
this.HasRequired(t => t.Register).WithOptional(r=>r.CustomerDisplay);
请注意,您不需要使用 HasForeignKey
来指定 CustomerDisplay.CustomerId
是 FK。这是因为 Entity Framework 要求将依赖项的主键用作外键。由于别无选择,Code First 只会为您推断这一点。
更新
如果您不能将CustomerDisplay
导航属性添加到Register
类中,那么我建议您创建一个单向的一对一关系。使用此配置:
this.HasRequired(t => t.Register);
这足以告诉 EF 在你们的关系中谁是主体,谁是依赖实体。
关于c# - 多重性在关系 : EF code first one to one relationship with same primary key and foreign key 中的角色中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32039873/