簡體   English   中英

使用dbcontext的正確方法(全局或傳遞為參數?)

[英]Proper way to use dbcontext (Global or pass as parameter?)

當我調用一個需要dbcontext進行updateinsert但只需要一個saveChange() ,如下所示

行動:登錄

        TempDBEntity context = new TempDBEntity();
        var temp = context.Users.Where(m => m.user_unique_id == 1).FirstOrDefault();
        temp.timestamp = new DateTime();
        temp.AddLog("Login");
        context.SaveChanges();

功能:AddLog

public void AddLog(string activity){
        TempDBEntity context2 = new TempDBEntity();
        var log = new UserLog();
        log.user_id = this.user_id;
        log.activity = activity;
        context2.UserLog.Add(log);
        context2.SaveChanges();
 }

如您所見,有兩個SaveChanges() ,我只需要1個SaveChanges()

我應該將DBContext作為AddLog()另一個參數傳遞,還是應該在這種情況下為dbcontext聲明靜態變量?

非常感謝。

在你的情況下,我會在你需要的方法中創建一個新的dabtase上下文,因為這是最簡單的方法,你可以非常好地重用你的方法。

這不應該產生很多性能問題,因為實體框架會緩存數據庫上下文中的所有重要信息,因此創建一個新的非常快。

如果你想優化事務量,那么我會編寫一種處理程序,它實現了它自己的SaveChanges方法並為每個實例保存一個數據庫上下文。 比你有一個更多的抽象層和一個很好的API供以后使用。

這是一個簡單的例子:

class UserLogin
{
    private TempDBEntity dbContex;

    UserLogin()
    {
        // ctor create dbContext
    }

    void Login()
    {
        // Login...
    }

    void AddLog()
    {
        // ...
    }

    void SaveChanges()
    {
        //dbContext.SaveChanges()...
    }
}

在我看來,傳遞dbcontext作為參數不是一個很好的解決方案。 但這是基於意見的......

您可以使用dbcontext,如下所示:

行動:登錄

using(TempDBEntity context = new TempDBEntity())
{
   var temp = context.Users.Where(m => m.user_unique_id == 1).FirstOrDefault();
   temp.timestamp = new DateTime();
   temp.AddLog("Login", context);
}

功能:AddLog

public void AddLog(string activity, TempDBEntity context)
{
    var log = new UserLog();
    log.user_id = this.user_id;
    log.activity = activity;
    context.UserLog.Add(log);
    context.SaveChanges(); 
}

這將在使用后正確處理對象。

I think you don't need to create new context in your AddLog function, you can pass the same first context to your AddLog function and then add your UserLogs to that without calling savechanges like this-

public void AddLog(TempDBEntity context, string activity){
        var log = new UserLog();
        log.user_id = this.user_id;
        log.activity = activity;
        context.UserLog.Add(log);
 }

暫無
暫無

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

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