简体   繁体   English

可以为实体框架模型创建包装器类吗?

[英]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: 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? 我想为我的模型类做包装,而不是直接在CRUD操作中使用我的模型,这样做是对的吗?

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. 我认为您是出于通信目的而使用模型(或更确切地说,我会说DTO对象)。

If you add wrapper than you need to also map it back to your DTOs. 如果添加包装器,则还需要将其映射回DTO。 (AutoMapper can be helpful) (AutoMapper可能会有所帮助)

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) 一种情况是在WPF或Silverlight中编写您需要更改感知模型的应用程序(即,实现INotifyPropertyChanged接口的模型)

Also , if you need to extend the behavior of your model , think about the extension methods before inheritance. 另外,如果需要扩展模型的行为,请在继承之前考虑扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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