c# - 多重性在关系 : EF code first one to one relationship with same primary key and foreign key 中的角色中无效

标签 c# entity-framework ef-code-first one-to-one ef-fluent-api

我有两个具有一对一关系的实体,其中目标实体的主键和外键相同。这是两个实体及其流畅的映射。

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);
    }
}

我收到以下错误:

enter image description here

我在 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/

相关文章:

entity-framework - 使用 autofac 注册多个 dbcontext

entity-framework - 从任意查询中提取强类型数据上下文实例

entity-framework-4 - 模拟DbContext.Set <T>()吗?

c# - 从数据库创建代码优先 poco 类

c# - 通过 Parallel 类 API 中的 ParallelOptions 参数提供 TaskScheduler 选项的真正目的

entity-framework - 将 sql View 映射到 EF 6 中的现有实体?

c# - 带 IDownloadManager 的 Windows 窗体 Webbrowswer 控件

domain-driven-design - 使用 EF 4.1,复杂类型能否引用实体(例如,在 DDD 中,值​​对象引用实体)?

c# - 如何让普通的 WebRequest 异步且可等待?

c# - XAML 中的命名空间