Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store enums in sql-server using Linq-to-sql

How do you store enums in sql-server using linq-to-sql?

I end up having a lot of conversions to and from int in my code. 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.

Could it be solved by an extension method to my linq-to-sql-classes and if so what would that look like?

like image 240
tomsv Avatar asked Oct 20 '11 14:10

tomsv


1 Answers

You can use a mapping for types from the database from within the DBML editor.

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):

  • open the DBML editor,
  • 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; for safety, use global::<namespace>.<type>.

like image 111
Grant Thomas Avatar answered Oct 25 '22 07:10

Grant Thomas