Entity Framework - Permanent Transitions in General?

Trying to create a workaround to handle Enums in the Entity Framework using Generics, but EF does not seem to care about the general properties. For instance:

public enum MyEnum { One, Two, Three } public class SomePOCOWithEnum { // I want this to persist as an int, but EF doesn't like generics. public EnumWrapper<MyEnum> MyEnumProperty { get; set; } } 

The goal is to keep the enumeration as an INT in the database. Is there any special way to use the free, or possibly another mechanism, with which I can create the specified common class and save it as an INT in the database in EF?

The goal is to preserve the general properties, since I have about two dozen transitions that need to be preserved, and I would prefer not to write separate wrapper classes for each of them.

Here is a generic EnumWrapper class that demonstrates what I would like to accomplish: implicit conversion to enum, but persistence as int:

 public class EnumWrapper<T> where T : struct { private T enumValue; public int Value { get { return Convert.ToInt32(enumValue); } set { enumValue = (T)Enum.Parse(typeof(T), value.ToString()); } } public T EnumValue { get { return enumValue; } set { enumValue = value; } } public static implicit operator T(EnumWrapper<T> wt) { return wt.EnumValue; } public static implicit operator EnumWrapper<T>(T t) { return new EnumWrapper<T>() { EnumValue = t }; } public override string ToString() { return enumValue.ToString(); } } 
+6
source share
1 answer

As mentioned earlier, EF5 has explicit support for Enums, but if you cannot switch to it for any reason, the approach I took may work for you.

In this example, let's say that the table is called β€œEmail,” and we have a column called β€œPriority.” Set the column as int, as usual. Then, in your entities project, create an enumeration class that will map to your int values:

 public enum EmailPriorityEnum { Now = 100, Soon = 1000, Whenever = 10000 } 

Finally, in the project of your entities, create a file with a partial class that matches your object and manually map it by enumeration:

 public partial class Email { public EmailEnums.EmailPriorityEnum EmailPriority { get { return (EmailEnums.EmailPriorityEnum)Priority; } set { Priority = (int)value; } } } 

From there, your code can reference this property transparently. The main disadvantages of this approach are:

  • You must be careful that all possible values ​​are displayed in an enumeration with the corresponding identifiers. For listings that change frequently, this becomes problematic.
  • Developers will still have access to the base column, unless you change the accessibility and, perhaps, can bypass the enumerations and use whatever value they like.
+4
source

Source: https://habr.com/ru/post/904737/


All Articles