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我結束了交易。