【问题标题】:Can a foreign key column be an Enum in Entity Framework 6 code first?外键列可以首先是 Entity Framework 6 代码中的枚举吗?
【发布时间】:2015-03-26 16:03:46
【问题描述】:

我首先将 EF5 DB 转换为 EF6 代码。在旧设置中,有一些 FK 是字节。并在应用程序中映射到具有下划线类型的字节的枚举。效果很好。

首先转到代码和 EF6,我发现枚举应该“正常工作”的说法,实际上对于常规列似乎就是这种情况。我可以从这里开始

public byte FavPersonality {get;set;}

到这里:

public Personality FavPersonality {get;set;}

但是当涉及到也是外键的列时,我得到了这个错误:

System.ArgumentException : The ResultType of the specified expression is not
compatible with the required type. The expression ResultType is 'Edm.Byte'
but the required type is 'Model.Personality'. 

这是 EF6 + Code first 无法完成的事情吗?

编辑:

枚举定义为 :byte

【问题讨论】:

  • 您的枚举是否在名称后使用“: byte”定义?

标签: c# enums foreign-keys entity-framework-6


【解决方案1】:

我刚刚遇到了同样的问题,我的枚举是一个基本数字枚举,但这是按消息搜索的第一个结果。我的主要对象上有一个子类型,其中的值是一组固定的值。但是,它们也有对象,因此我们可以针对它们编写查询。

public class Foo {
    [Key]
    public int Id { get; set; }

    public BarEnum BarId { get; set; }

    [ForeignKey(nameof(BarId))]
    public Bar Bar { get; set; }
}

public class Bar {
    [Key]
    public int Id { get; set; }
}

public enum BarEnum {
    Type1,
    Type2
}

此配置给了我与此问题中描述的相同的错误消息:

指定表达式的ResultType不是 与所需类型兼容。表达式 ResultType 是 'BarEnum' 但所需的类型是“Edm.Int”。

解决方法很简单:只需将 Bar 的 ID 更改为也使用枚举,一切正常。这是有道理的,因为int 的可能值比BarEnum 的值要多得多。

public class Bar {
    [Key]
    public BarEnum Id { get; set; }
}

【讨论】:

  • 已经有一段时间了,我的代码早就不见了,如果有人可以确认这回答了问题,我会标记它。
  • 没问题。就像我说的,这是我搜索错误文本时的最佳结果。寻找所有使用外键的地方是一件苦差事,但一旦我这样做了,它就像一个魅力。
【解决方案2】:

编辑 - 根据@krillgars answer,在现代 EF 中,最好只使用实际的枚举类型作为主键(和引用的外键) - EF6 和 EfCore 可以很好地映射这一点。

旧答案

我也得到了错误:

指定表达式的 ResultType 为 MyEnum 与所需的类型“Edm.Int32”不兼容。参数名称:keyValues[0]

使用枚举映射时:

[Column("MyActualFKColumnId", TypeName = "int")]
public MyEnum MyEnum { get; set; }

// NB : Foreign Key refers to the C# Property, not the DB Field
[ForeignKey("MyEnum")]
public MyEntityReferencedByEnum MyEntityReferencedByEnum { get; set; }

但是,我能够通过恢复原始整数外键 (MyActualFKColumnId)、删除 [Column][ForeignKey] 属性,然后向类添加 [NotMapped] 属性破解来解决上述问题:

[NotMapped]
public MyEnum MyEnum
{
    get { return (MyEnum) MyActualFKColumnId; }
    set { MyActualFKColumnId=(int)value; }
}

【讨论】:

    【解决方案3】:

    当 PK 与 FK 与子实体不匹配时,您可能会收到此错误。例如,当使用列顺序与 FK 不匹配的复合 PK 时。像这样:

    class Foo
    {
        [Key, Column(Order=10)]
        int Pk1 {get; set;}
    
        [Key, Column(Order=20)]
        short Pk2 {get; set;}
    
        [ForeignKey("Pk2,Pk1")] // <== ORDER DOESN'T MATCH PK OF CHILD ENTITY
        Foo Child {get;set;}
    }
    

    使用上面的代码,EF 将尝试将表Foos 与自身连接,但列纵横交错,因此它们的类型将不匹配。

    【讨论】:

      猜你喜欢
      • 2015-02-17
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多