c# - 外键列可以首先是 Entity Framework 6 代码中的枚举吗?

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

我首先将 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

最佳答案

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

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
}

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

The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'BarEnum' but the required type is 'Edm.Int'.

这个问题的解决方案很简单:只需更改 Bar 的 Id 以也使用枚举,一切正常。这确实有道理,因为 int 的可能值比 BarEnum 的可能值

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

关于c# - 外键列可以首先是 Entity Framework 6 代码中的枚举吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283361/

相关文章:

c# - 将 KeyDown 键转换为一个字符串 C#

c++ - 枚举协方差/多态性?

mysql - 外键,障碍多多有用?

enums - 与数组上的迭代相比,使用 Arrays.stream() 是否有任何性能优势?

MySQL外键使用id还是value?

mysql - 无法添加或更新子行: a foreign key constraint fails - OneToMany

c# - 线程专有数据 : how to store and access?

c# - 来自属性设置函数的 WPF 数据验证

c# - 反序列化数组总是为元素返回 null 但适用于属性

typescript - 在 Typescript 对象中提取 ENUM 的字符串值