使用枚举作为主键与EF [英] Using an enum as a primary key with EF

查看:232
本文介绍了使用枚举作为主键与EF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to use an enum as a primary key for a table? I have something like the following:

public enum SpecialId : uint {}

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

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

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

But i get the following error on initialisation:


EntityFramework.dll中出现类型为System.InvalidOperationException的未处理异常。

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

附加信息:关键组件Id不是Thing类型上声明的属性。验证它没有被明确排除在模型之外,并且它是一个有效的原始属性。

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.

一个原始的(一个枚举只能被渲染为primitave),而 EF在枚举周围的帖子 sugdest这是可能的

This does say it needs to be a primitive (an enum is only castable to primitave) but the EF post around enums sugguests this is possible


枚举为键

Enums as keys

此外,枚举类型的属性可以参与主键,唯一约束和外键的定义,以及参与并发控制检查,并声明为默认值。 p>

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.

我做错了,还是不支持?

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

On a side not I know that I could hack in this functionality using another property with not mapped on it to translate keys to enums. This is not the answer I am looking

推荐答案

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

This does not work because your enum is based on uint. EF does not support unsigned integral types in general (i.e. you could use the uint type for a property) and therefore it won't work for enum properties as well.

I我个人不是枚举键的大粉丝。这里有几个原因:

I am personally not a big fan of enum keys. Here is just a couple of reasons:


  • 数据库中的值可以非常容易地与您的枚举定义
  • 失去同步
  • 如果数据库生成密钥,则可以将其分解开 - 通常数据库从1开始生成ID,但第一个枚举成员为0

  • 枚举类型通常具有只是一些常数/成员。虽然可能具有在枚举底层类型的范围内但在枚举类型中没有相应常量的值(并且EF支持这一点),但是这违反了使用枚举类型
  • $ b的目的$ b
  • the values in the database can get out of sync very easily with your enum definition
  • this can be broken out of box if the database generates the keys - typically database starts generating IDs from 1 but the first enum member is 0
  • enum types typically have just a few constants/members. While it is possible to have values that are in the range of the enum underlying type but don't have a corresponding constant in the enum type (and EF supports this) this defeats the purpose of using the enum type

这篇关于使用枚举作为主键与EF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆