【问题标题】:EntityFramework anonymous composite key property name conflictEntityFramework 匿名复合键属性名冲突
【发布时间】:2012-12-05 16:40:10
【问题描述】:

我正在使用 EntityFramework 5(或 .Net Framework 4.0 的 4.3)

在我的 DbContext 对象中,我已经设置了正确的 DbSet,并且这些对象包含对彼此的正确引用。这对我来说并不新鲜,而且一切都很好。

现在在这种情况下,我有一些复合键,有时包括表(或本例中的对象)的外键。为此,我在 DbContext 的 OnModelCreating 方法上使用了 HasKey<>() 函数。当这些属性名称不同时,没有问题,但是当这些属性名称相同时,则无法进行迁移。

一个例子:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // ...

        modelBuilder.Entity<PatientVisit>().ToTable("PatientVisits");
        modelBuilder.Entity<PatientVisit>().HasKey(x => 
            new { x.Patient.Code, x.Code });

        // ...

        base.OnModelCreating(modelBuilder);
    }

正如您在提供的代码中看到的,对象 PatientVisit 有一个名为 Code 的属性,但只要与不同的患者重复此属性,就可以重复此属性。实体 Patient 还定义了一个名为 Code 的键。

匿名类型不能有两个属性推断同名(很明显)。典型的解决方案是像这样命名匿名类型的属性:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // ...

        modelBuilder.Entity<PatientVisit>().ToTable("PatientVisits");
        modelBuilder.Entity<PatientVisit>().HasKey(x => 
            new { PatientCode = x.Patient.Code, VisitCode = x.Code });

        // ...

        base.OnModelCreating(modelBuilder);
    }

但是这样做,当我尝试添加迁移时,会抛出此错误消息。

The properties expression 'x => new <>f__AnonymousType3`2(PatientCode 
= x.Patient.Code, VisitCode = x.Code)' is not valid. The expression 
should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t)
t.MyProperty'. When specifying multiple properties use an anonymous 
type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  
VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

【问题讨论】:

    标签: c# ef-code-first anonymous-types entity-framework-4.3 entity-framework-migrations


    【解决方案1】:

    我认为您需要在这里做的是给PatientVisit 一个新属性PatientCode。这将是Patient 的外键。例如

        HasRequired<PatientVisit>(v => v.Patient).WithMany()
                                                 .HasForeignKey(v => v.PatientCode)
    

    那你就可以了

        modelBuilder.Entity<PatientVisit>().HasKey(x => 
            new { x.PatientCode, x.Code });
    

    【讨论】:

    • 我知道有些解决方案需要我手动添加引用对象的键和 ID,但这意味着将简单对象模型“更改”为数据库映射模型,我不想这样做那个。
    • 您的解决方案与我实现的解决方案类似,只是不需要流畅的映射,因为它是由 DataAnnotations 完成的。基本上,它使用ForeignKey 属性将声明的属性附加到虚拟导航属性的外键......但它仍然暗示我必须明确定义导航属性 锚或外键属性。我想要一个整洁、干净的对象模型,没有任何与数据库相关的关键属性。
    • 有关我所指的 current-but-not-wanted 解决方案的示例,请参阅this thread,其中有很好的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    相关资源
    最近更新 更多