Search code examples
asp.netentity-framework-6

Entity Framework Class Manipulation


I'm using Entity Framework (DB First) on a new project and wanted to add some customisation to the classes generated. However, my changes are obviously lost every time that the edmx is refreshed. I was just wondering if there is a design pattern for handling this sort of thing?

As an example, suppose I have a class with a integer property; StatusID - and I'd like to extend the entity class so that the status value can also be accessed/set via the related enum and finally a property that gets a text representation of that Enum from the description attribute. This all works, but those customisations are lost when the model is refreshed. I appreciate that the property can be converted to an enum, so the latter property that gets the description of the enum is perhaps a better example for this question.

I think I know the answer but I just wanted to put this out there in case there were some magic tricks that would allow this to work and prevent those customisations from being lost.

    public int StatusID { get; set; }

    public Enumerations.ValidationStatus StatusEnum
    {
        get
        {
            return (Enumerations.ValidationStatus)StatusID;
        }
        set
        {
            StatusID = (int)value;
        }
    }

    public string StatusText
    {
        get
        {
            return MyMethodThatGetsTheEnumDescription(StatusEnum);
        }
    }

Solution

  • Two Solutions to work around the problem:

    1. User Data Transfer Object(DTO) nd put the enum there. then use Automapper or manually map between the DB Model and the DTO Model (best practice)
    2. Instead of enum you can use extension functions on the model and define your getter, setters and any extra properties you want as extension functions to the class (will add some complexity to your models)