How to map Enum to char(1) in LINQ-to-SQL?
I have an enum that maps to possible field values in a char(1) field on DB.
public enum TestEnum: char
{
Value1 = 'a',
Value2 = 'b',
...
}
LINQ-to-SQL tries to map char fields as values like they are the names开发者_如何学Go of the enums. For instance for the value of "a" LINQ-to-SQL tries to find the value TestEnum.a
instead of TestEnum.Value1
and that causes an exception. It only supports value-based enum mapping for integer fields.
It's possible to create a new property that handles the conversion but that fails to behave well in queries because of the expression generated does not map to the underlying field directly.
Is there another way to make LINQ-to-SQL to use enum value for mapping against char(1)?
Here is what we're doing now:
We use System.Char
as underlying type and typecast during assignment. For instance:
entity.SomeField = (char)TestEnum.Value1;
And we use Equals
in queries, such as:
where entity.SomeField.Equals(TestEnum.Value1);
.Equals
makes the conversion. If you typecast here instead SQL server adds an unnecessary NVarChar(1)
-> Char(1)
conversion. .Equals
syntax doesn't do that and behaves correctly for some reason.
精彩评论