c# - EntityFramework 匿名复合键属性名称冲突

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

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

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

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

一个例子:

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 }'.

最佳答案

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

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

然后你可以做

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

关于c# - EntityFramework 匿名复合键属性名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933569/

相关文章:

c# - 如何获取表单的截图

c# - MVC Web 框架和 Mono

c# - 如何使用 Entity Framework 在 FluentAPI/Data Annotations 中定义外键可选关系?

entity-framework - .WithMany() 和 .WithOptional() 的区别?

java - 匿名内部类(相对于非匿名内部类)有哪些优势?

C# 数据适配器参数

c# - 外部窗口上的图像叠加

entity-framework - EF 代码第一个 : Treating entity like a complex type (denormalization)

c# - LINQ 如何在 lambda 表达式中选择超过 1 个属性?

c# - 如何将 List<Anonymous Type> 转换为 List<string>