簡體   English   中英

來自數據庫的EF 6模型,該將上下文放在哪里?

[英]EF 6 model from database, where do I put the context?

我正在使用Entity Framework6。我使用它從現有數據庫生成類。 我正在使用另一個局部類向這些類添加一些字段和方法。 我的問題是我應該把上下文放在哪里。

即我創建了一個新的構造函數,該構造函數接受上下文並創建一個新的對象並將其添加到上下文中:

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,所以結束了交易。

您的直覺是正確的,無論是嘗試使用構造函數注入,還是不願意在模型類中使用數據訪問邏輯。 一個替代的實現是這樣的:

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更改為公共屬性。

暫無
暫無

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

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