正确的方法使用的DbContext(全球通或作为参数?) [英] Proper way to use dbcontext (Global or pass as parameter?)

查看:788
本文介绍了正确的方法使用的DbContext(全球通或作为参数?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用一个方法需要的DbContext 更新插入
但只希望有一个 saveChange()类似以下

When I call a method that need dbcontext for update or insert but only want one saveChange() like following

操作:登录

        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 静态变量?

Should I pass DBContext as another parameter for AddLog() or should I declare static variable for dbcontextin this case?

非常感谢。

推荐答案

在你的情况我会创造在你需要它的方法一个新的dabtase的背景下,因为这是最简单的方法,你可以重用你的方法很不错。

In your case i would create a new dabtase context in the method you need it, because this is the easiest way and you can reuse your methods very good.

这不应该使大量的性能问题,因为实体框架缓存在数据库环境中的所有重要信息,从而创建一个新的非常快。

This should not make a lot of performance problems, because entity framework cache all important information over the database context, so creating a new one is very fast.

如果你想优化交易的金额,比我会写一种处理程序,它实现了它自己的的SaveChanges 方法并保持每个实例一个DATABSE上下文。比你多了一个抽象层,以备后用一个漂亮的API。

If you want optimize the amount of transactions, than i would write a kind of handler, which implements it's own SaveChanges method and hold one databse context per instance. Than you have one more abstraction layer and a nice API for later use.

下面是一个简单的例子:

Here is a simple example:

class UserLogin
{
    private TempDBEntity dbContex;

    UserLogin()
    {
        // ctor create dbContext
    }

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

    void AddLog()
    {
        // ...
    }

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

传递一个作为的DbContext参数是我的观点不是一个非常好的解决方案。但是,这是基于意见了......

Passing a dbcontext as parameter is in my point of view not a very good solution. But this is opinion based...

这篇关于正确的方法使用的DbContext(全球通或作为参数?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆