加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:50:47 所属栏目:百科 来源:网络整理
导读:我正在使用EntityFramework 5(或.Net Framework 4.0的4.3) 在我的DbContext对象中,我已经设置了正确的DbSet,并且对象包含对彼此的正确引用.这对我来说并不新鲜,事情也很顺利. 现在在这种情况下,我有一些复合键,有时包括表的外键(在这种情况下是对象).为此,我
我正在使用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 });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读