簡體   English   中英

可以為實體框架模型創建包裝器類嗎?

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

模型:

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; }

}

包裝類:

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; }

}

實現方式:

public void AddStudent()
{

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

      ctx.Student.Add(newStudent);
   }

}

我想為我的模型類做包裝,而不是直接在CRUD操作中使用我的模型,這樣做是對的嗎?

恕我直言,

除非您想在包裝器中編寫一些自定義邏輯,否則這不是一個好主意。 我認為您是出於通信目的而使用模型(或更確切地說,我會說DTO對象)。

如果添加包裝器,則還需要將其映射回DTO。 (AutoMapper可能會有所幫助)

因此,除非您有非常具體的理由要這樣做,否則為我創建包裝器沒有任何意義。 一種情況是在WPF或Silverlight中編寫您需要更改感知模型的應用程序(即,實現INotifyPropertyChanged接口的模型)

另外,如果需要擴展模型的行為,請在繼承之前考慮擴展方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM