Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL strings to enums

Tags:

linq-to-sql

LINQ to SQL allows table mappings to automatically convert back and forth to Enums by specifying the type for the column - this works for strings or integers.

Is there a way to make the conversion case insensitive or add a custom mapping class or extenstion method into the mix so that I can specify what the string should look like in more detail.

Reasons for doing so might be in order to supply a nicer naming convention inside some new funky C# code in a system where the data schema is already set (and is being relied upon by some legacy apps) so the actual text in the database can't be changed.

like image 857
Ronnie Avatar asked Aug 07 '08 16:08

Ronnie


People also ask

How to convert string to string enum?

To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.

Can you cast string to enum?

IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

How to pass string value to enum in c#?

Parse the string value into an Enum Enum. Parse(Type enumType,string value) - This method directly parses the string representation of the name or numeric value of enum member into enumType object. If the string representation of the name is not found, then it will give the exception.

How to store enum in database c#?

No need to convert (int)Enum or (Enum)int in code. Just use the enum and ef code first will save the int for you. p.s.: "[EnumDataType(typeof(PhoneTypes))]" attribute is not required, just an extra if you want additional functionality.


1 Answers

You can always add a partial class with the same name as your LinqToSql class, and then define your own parameters and functions. These will then be accessible as object parameters and methods for this object, the same way as the auto-generated LinqToSql methods are accessible.

Example: You have a LinqToSql class named Car which maps to the Car table in the DB. You can then add a file to App_Code with the following code in it:

public partial class Car {
  // Add properties and methods to extend the functionality of Car
}

I am not sure if this totally meets your requirement of changing the way that Enums are mapped into a column. However, you could add a parameter where the get/set properties will work to map the enums that you need while keeping things case-insensitive.

like image 81
Yaakov Ellis Avatar answered Oct 12 '22 22:10

Yaakov Ellis