Home > Software design >  How to set the variables in a class that has been generated by Entity Framework from another partial
How to set the variables in a class that has been generated by Entity Framework from another partial

Time:05-27

I need to add an constructor to a class which is automatically generated by EF, from my understand to enhance any class created by EF you'd create another partial class with the same name, so for example my EF generated class:

public partial class MyCoolClass  // EF CLASS
{
    public string VariableOne { get; set; }
    public string VariableTwo { get; set; }
}

I'd then create another partial class as:

public partial class MyCoolClass  // MY CLASS
{    
   public MyCoolClass(Foo fooObject) 
   {
        VariableOne = fooObject.Var1 // VariableOne doesn't exist
   }
}

However, I'm unable to reference VariableOne and VariableTwo in the EF generated class, can you not do this?

Reason I ask this question, is because my EF class has roughly 20-30 variables and having to declare a new instance of that class and then populate each field within the code is tedious, and I'd like to move that logic of setting the variables into a constructor.

CodePudding user response:

The only reason for the missing variable can be that you have both classes in different namespaces. Partial classes are generally the same class split into 2 or more files.

So, give the both classes the same namespace, independent from where are they placed and try again:

Folder: Entities

namespace Same.Namespace.Location
{
    public partial class MyCoolClass
    {
        public string VariableOne { get; set; }

        public string VariableTwo { get; set; }
    }
}

Folder: Models (for instance ...)

namespace Same.Namespace.Location
{
    public partial class MyCoolClass
    {
        public MyCoolClass(Foo fooObject)
        {
            this.VariableOne = fooObject.Var1; 
        }
    }
}

... and all Properties are there again.

  • Related