小编Isa*_*pis的帖子

EntityFramework匿名复合键属性名称冲突

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

在我的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);
    }
Run Code Online (Sandbox Code Playgroud)

正如您在提供的代码中看到的那样,对象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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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#: …
Run Code Online (Sandbox Code Playgroud)

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

7
推荐指数
1
解决办法
2475
查看次数

如何在实体框架中使用 Fluent API 映射一对多关系中的枚举?

我的问题很简单,并且与另一个问题相关(How to map an enum in a one-to-many relationship with NHibernate?),尽管在这里我特别询问实体框架的流畅 API。

假设(同一示例)我的模型中有这两个实体,一个引用类型(用户),另一个枚举(角色)。

class User { int id; IList<Roles> Roles; }

enum Roles { Worker, Manager, Director }
Run Code Online (Sandbox Code Playgroud)

或者为了清楚起见,在这个表示中......

[users]   [ roles ] 
+-----+   +-------+
| id  |   |user_id|
+-----+   +-------+
          | value | <- [Represented by the enum]
          +-------+
Run Code Online (Sandbox Code Playgroud)

现在我想使用 Fluent API 将其映射到实体框架中的数据库,但如果我尝试...

 HasMany(x => x.Roles)
   .Cascade.All()
   .Table("UserRoles")
   .Element("RolesEnum");
Run Code Online (Sandbox Code Playgroud)

...它将失败,因为HasMany()不是引用类型。

有没有一种方法可以在流畅的 API 中做到这一点,而不涉及将我的业务模型从枚举更改为类?

c# enums entity-framework

5
推荐指数
1
解决办法
3256
查看次数