简体   繁体   English

使用Linq-to-sql在enql-server中存储枚举

[英]Store enums in sql-server using Linq-to-sql

How do you store enums in sql-server using linq-to-sql? 如何使用linq-to-sql在sql-server中存储枚举?

I end up having a lot of conversions to and from int in my code. 我最终在我的代码中进行了大量的int转换。 There has to be a better way. 一定有更好的方法。 What did I miss? 我错过了什么?

sqlItem.enumValue = (int)myEnumValue;
...
myEnumValue = (MyEnumType)sqlItem.enumValue

It does not matter if SQL server or LINQ stores the values as strings or ints in the database, I just want to avoid all these typecasts sprinkled all over my code. 如果SQL服务器或LINQ将值存储为数据库中的字符串或整数并不重要,我只想避免所有这些类型转换遍及我的代码。

Could it be solved by an extension method to my linq-to-sql-classes and if so what would that look like? 它可以通过我的linq-to-sql-classes的扩展方法解决,如果是这样的话会是什么样的?

You can use a mapping for types from the database from within the DBML editor. 您可以在DBML编辑器中使用数据库中的类型映射。

Assuming you're working from within Visual Studio (the order in which these actions are undertaken can get highly irritating, since it auto-deselects your current selection in the editor when opening the properties, and so on): 假设您在Visual Studio中工作(执行这些操作的顺序会非常恼人,因为它在打开属性时会自动取消选择编辑器中的当前选择,等等):

  • open the DBML editor, 打开DBML编辑器,
  • open the "Properties" view/tab 打开“属性”视图/选项卡
  • specify the type in the "Type" field. 在“类型”字段中指定类型。

In my experience, just inputting the type in the form of <namespace>.<type> is not always successful, I think this is the nuance that @leppie is referring to; 根据我的经验,只需以<namespace>.<type>的形式输入类型并不总是成功,我认为这是@leppie所指的细微差别; for safety, use global::<namespace>.<type> . 为安全起见,请使用global::<namespace>.<type>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM