c# - 在 EF 中使用枚举作为主键

标签 c# entity-framework

是否可以使用枚举作为表的主键?我有类似以下内容:

public enum SpecialId : uint {}

public class Thing 
{
     public SpecialId Id { get; set; }
}

public class MyContext : DbContext
{
     public DbSet<Thing> Things { get; set; }
}

但是我在初始化时收到以下错误:

An unhanded exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: The key component 'Id' is not a declared property on type 'Thing'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

这确实说明它需要是原始类型(枚举只能转换为原始类型)但是 EF post around enums表明这是可能的

Enums as keys

In addition, properties of enum types can participate in the definition of primary keys, unique constraints and foreign keys, as well as take part in concurrency control checks, and have declared default values.

是我做错了什么还是这根本不受支持?

另一方面,我不知道我可以使用另一个未映射的属性来破解此功能,以将键转换为枚举。这不是我正在寻找的答案

最佳答案

这不起作用,因为您的枚举基于 uint。 EF 通常不支持无符号整数类型(即您可以将 uint 类型用于属性),因此它也不适用于枚举属性。

我个人不是枚举键的忠实粉丝。这只是几个原因:

  • 数据库中的值很容易与您的枚举定义不同步
  • 如果数据库生成 key ,这可以开箱即用 - 通常数据库从 1 开始生成 ID,但第一个枚举成员是 0
  • 枚举类型通常只有几个常量/成员。虽然可能具有在枚举基础类型范围内但在枚举类型中没有相应常量的值(并且 EF 支持这一点),但这违背了使用枚举类型的目的

关于c# - 在 EF 中使用枚举作为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35211570/

相关文章:

asp.net - DbContext VS ObjectContext

c# - List<>.Exists() 在 WP7 中不存在?

C# 延迟初始化 && 初始化竞赛?

c# - 类成员初始化的简写

c# - Lucene.Net QueryParser 抛出 IOException(读取过去的 eof)

c# - List<> 在 ToArray() 期间丢失的项目?

linq - LINQ OrderBy不订购..什么都没有改变..为什么?

c# - UserManager 不断抛出 System.ArgumentNullException

c# - "res://*/"中的 * 是什么意思?

c# - 如何模拟 Entity Framework 的接口(interface)?