微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用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 }'.

解决方法

我认为你需要做的是给PatientVisit一个新的属性PatientCode.哪个是患者的外键.例如
Hasrequired<PatientVisit>(v => v.Patient).WithMany()
                                             .HasForeignKey(v => v.PatientCode)

那你可以做

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

原文地址:https://www.jb51.cc/csharp/99663.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐