11

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?

1 Answer 1

16

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>.

Sign up to request clarification or add additional context in comments.

8 Comments

Also make sure the enum is defined in the same namespace as the DataContext, else it fails :\
Hmm, or was it was to include the using statement within the namespace? Too long to remember :)
@leppie Indeed I did, fixed; I think my updated appropriately addresses the issue you bring up - could you perhaps confirm this for your case?
It is in a codebase somewhere :) Will try look for it. We are not owners of that code anymore.
If I do this, will I lose these changes when I resynchronize the model with the sql database by deleting all the tables from the designer and then re-adding them to the designer?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.