2014-09-29 51 views
0

我正在使用Entity Framework 6.我用它從現有數據庫生成我的類。我正在使用另一個部分類爲這些類添加一些字段和方法。我的問題是我應該在哪裏放置上下文。來自數據庫的EF 6模型,我在哪裏放置上下文?

即我創建了一個新的構造函數,把我的背景,並創建一個新的對象,並將其添加到 背景:

public partial class EntityClass1 
{ 
    private readonly EntitiesContext dbContext; 
    private String customString1; 
    private bool justInitialized; 

    public EntityClass1(EntitiesContext dbContext) 
    { 
     this.dbContext = dbContext; 
     dbContext.EntityClass1.Add(this); 
     customString1 = "voila"; 
     justInitialized = true; 
    } 

    public MethodUpdateString() 
    { 
     customString1 = "UPDATED"; 
     var entity2 = new EntityClass2(); 
     entity2.EntityClass1Id = this.Id; 
     dbContext.EntityClass2.Add(entity2); 
     dbContext.SaveChanges(); 
    { 
} 

public partial class EntityClass2 
{ 
    //Some code here 
} 


public MainClass{ 
    static void Main(){ 
     using (var dbContext = new EntitiesContext()) 
     { 
      //other operations on the context here 

      var e1 = new EntityClass1(dbContext); 
      e1.MethodUpdateString(); 

      //other operations on the context here 
     } 
    } 
} 

我不知道爲什麼,但我這個可能的實現不是很舒服。例如向方法MethodUpdateString()添加上下文參數會更好嗎?另外,因爲我做了SaveChamges我結束了交易。

回答

0

你的直覺是正確的,無論是在嘗試使用構造函數注入還是在模型類中都沒有數據訪問邏輯。另一種實現是這樣的:

public partial class EntityClass1Service 
{ 
    private readonly EntitiesContext dbContext; 

    public EntityClass1Service(EntitiesContext dbContext) 
    { 
     this.dbContext = dbContext; 
    } 

    public MethodUpdateString(EntityClass1 entityClass1Object) 
    { 
     entityClass1Object.CustomString1 = "UPDATED"; 
     dbContext.EntityClass1.Add(entityClass1Object); 
     var entity2 = new EntityClass2(); 
     entity2.EntityClass1Id = entityClass1Object.Id; 
     dbContext.EntityClass2.Add(entity2); 
     dbContext.SaveChanges(); 
    } 
} 

您可能還需要添加MethodUpdateString內try-catch塊,也許改變customString1是公共財產。