保存标志枚举在SQL数据库和EF6。这可能吗? [英] Save Flag Enums in SQL Database and EF6. Is this possible?

查看:116
本文介绍了保存标志枚举在SQL数据库和EF6。这可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET应用程序中我有一个标志枚举如下:

On an ASP.NET application I have a flag enum as follows:

[Flags]
enum Target : int {
  None = 0,
  Group = 1,
  Student = 2,
  Professor = 4,
  All = Group | Student | Professor
}



我能保存包含在一个SQL数据库表的多个项目的值使用实体框架6?

Can I save a value containing more than one item in a SQL Database Table using Entity Framework 6?

怎么会是得救?

感谢您,
米格尔

Thank You, Miguel

推荐答案

要放东西很简单,标志可以被看作是一个int总和(只是为了简单,但实际上他们按位操作的工作)。

To put things really simple, flags can be seen as an int sum (just to be simple but actually they work with bitwise operations).

因此,对于你的情况(提供枚举),如果记录有两个目标(学生和教授),最后的结果将是6。

So, for your case (provided enum), if a record has two targets (Student and Professor), the final result will be 6.

EF将存储仅此。 6.
你已经告诉EF应存储此列作为INT,因为你说,枚举应被理解为一个int在这里:

EF will store just this. 6. You have already told that EF should store this column as an INT because you've said that the enum should be understood as an int here:

enum Target : int {

有没有必要做任何事情(绝对的东西!)其他。

There is no need to do anything (absolutely anything!) else.

要得到这回学生和教授,还有就是你可以手动(仅在需要时)调用Enum.Parse但EF也将填充这个已经转换属性。

To get this back into both Student and Professor, there is an Enum.Parse that you can call manually (only when needed) but EF will also populate the property with this already converted.

在你的代码,你就不用担心只是代码。
所以,举例来说,你可以这样做:

On your code, you'll have to worry just about the code. So, for instance, you can do:

var item = new Something() { Prop = Target.Student | Target.Professor };
context.Save();

var item2 = context.GetSomething();

if (item2.Prop.HasFlag(Target.Professor) && item2.Prop.HasFlag(Target.Student))
{
   // WOW!
}

这只是它。
我用这与EF6并没有配置的。
至少有CodeFirst方法。

That's just it. I'm using this with EF6 and there is no configuration at all. At least with CodeFirst approach.

但不要忘了,这将只与.NET架构的更新版本。看看到从EF文档枚举支持主题。

But don't forget that this will work only with newer versions of .NET framework. Take a look into the Enum support topic from EF docs.

这篇关于保存标志枚举在SQL数据库和EF6。这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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