Search code examples
c#entity-frameworkpropertiescode-firstencapsulation

Is it possible to generate database fields without using C# properties in Entity Framework, code-first approach?


I am new on using the .NET Entity Framework (v6.1), following the code-first approach. I am using it on the creation of a native C# application.

I have created two classes, one base and one inherited:

public BaseClass
{
  public int ClassID { get; set; }
  //Rest of class properties/ctors/function definitions.
}

public DerivedClass : BaseClass
{
  //Rest of class properties/ctors/function definitions.
}

Additionally, I have set up a DbContext derived class using the fluent API in it in order to have Table per Type table mapping in the generated database.

I know that the Entity Framework uses the class properties in order to generate the database table fields. Because of some work project requirements, I want to define some "old-style" encapsulation logic classes in C#, defining fields and accessors/modifiers without properties and to generate tables via the EF code-first approach using those classes, for example:

public BaseClass
{
  private int _classID;
  public void SetClassID(int classID) {_classID = classID;}
  public int GetClassID() {return _classID;}

  //Rest of class properties/ctors/function definitions.
}

So, I would like to know, is there any way, trick or workaround to set the Entity Framework work with it (maybe generate fields based on private fields and not properties)? My google search did not provide any relevant results.

Thank you in advance.


Solution

  • The final solution I applied, was creating C# classes used from the Entity Framework containing C# properties, allowing the construction of C# objects using the tool-generated structures (same applies with classes):

    //Tool struct
    struct AStruct{
      int value;
    };
    
    //C# class used by EF:
    public class A{
        public int Value { get; set; }
    
        //Rest of ctors....
    
        public A(AStruct s)
        {
            Value = s.value;
        }
    
        public AStruct ToStruct(){
            return new AStruct
            {
                value = Value;
            }
        }
        //Rest of code here....
    }
    

    This did the trick, as EF uses pure C# classes, and I have "wrapped" in a sense the tool structures for EF.