加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用枚举作为EF的主键

发布时间:2020-12-15 23:30:57 所属栏目:百科 来源:网络整理
导读:是否可以使用枚举作为表的主键?我有以下内容: public enum SpecialId : uint {}public class Thing { public SpecialId Id { get; set; }}public class MyContext : DbContext{ public DbSetThing Things { get; set; }} 但是我在初始化时遇到以下错误: A
是否可以使用枚举作为表的主键?我有以下内容:

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.

这确实说它需要是一个原始的(枚举只能浇铸到primitave)但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类型),因此它也不适用于枚举属性.

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

>使用枚举定义,数据库中的值可能很容易失去同步>如果数据库生成密钥,则可以将其打开 – 通常数据库开始从1生成ID,但第一个枚举成员为0>枚举类型通常只有几个常量/成员.虽然可以使枚举基础类型的范围内的值但在枚举类型中没有相应的常量(并且EF支持这种情况),但这违背了使用枚举类型的目的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读