2013-04-02 55 views
0

型號:可以爲實體框架模型創建包裝類嗎?

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

} 

我想打一個包裝我的模型類而不是直接在增刪改查中使用我的模型,這樣做是否適合?

+1

請問這樣做的理由是什麼?你想寫一些代碼嗎? – TalentTuner

+0

我只是想使用該包裝將被用於添加新的學生,編輯和刪除。 – user2131005

回答

3

恕我直言,

它不是直到你想要寫在包裝一些自定義邏輯是個好主意。我認爲你正在使用你的模型(或者說我會說DTO對象)來進行通信。

如果你添加的包裝比你需要還映射回您的DTO。 (AutoMapper可以有所幫助)

因此,直到你有非常明確的理由來做這件事,而不是爲我創建包裝。其中一種情況是在WPF或Silverlight中編寫一個應用程序,在該應用程序中需要知道變化的模型(即實現INotifyPropertyChanged接口的模型)

另外,如果需要擴展模型的行爲,請考慮以下擴展方法遺產。

+0

在那個包裝器中,我打算添加,編輯,刪除方法 – user2131005

+0

同意Sauraph。如果你想對get set進行某種驗證,那麼它可能會有所幫助。 –

相關問題