简体   繁体   中英

Is it ok to create wrapper classes for entity framework models?

Model:

public class Student
{
    public int StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Gender Gender { get; set; }
    public string Address { get; set; }
}

DBContext:

public class MyContext : DbContext
{

   public MyContext():base(connectionstring)
   {
   }

   public DbSet<Student> Student { get; set; }

}

Wrapper Class:

public class StudentWrapper
{

    public int StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Gender Gender { get; set; }
    public string Address { get; set; }

}

Implementation:

public void AddStudent()
{

   using(MyContext ctx = new MyContext())
   {
      StudentWrapper newStudent = new StudentWrapper(); // If ever I wanted this `working`

      ctx.Student.Add(newStudent);
   }

}

I want to make a wrapper for my model classes instead of directly using my models in CRUD operations, is this right to do so?

IMHO,

It is not a good idea untill you want to write some custom logic in the wrappers. I think you are using your model ( or rather i would say DTO objects) for communication purpose.

If you add wrapper than you need to also map it back to your DTOs. (AutoMapper can be helpful)

So , until you have very specific reason to do this than it does not make sense to create wrapper to me. One of the scenario would be writing an application in WPF or Silverlight where you want a change aware model (ie Model implementing INotifyPropertyChanged Interface)

Also , if you need to extend the behavior of your model , think about the extension methods before inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM