【问题标题】:EntityFramework DbContext in static method per request每个请求的静态方法中的 EntityFramework DbContext
【发布时间】:2019-02-23 20:19:07
【问题描述】:

Entity Framework DbContext 如何在每个 Web 请求的静态方法中工作?有任何性能问题吗?我在下面有 2 节课。哪个更好用?还是不好?我们需要获取实例所有梨请求吗?有什么问题吗?

public class MyClassA 
{
    public static Product GetProduct(int Id) 
    {
        using(MyContext myContext = new MyContext())
        return myContext.Products.Where(x = > x.Id == Id).SingleOrDefault();
    }
}

public class MyClassB 
{
    MyContext myContext = new MyContext()

    public static Product GetProduct(int Id) 
    {
        return myContext.Products.Where(x = > x.Id == Id).SingleOrDefault();
    }
}

在控制器中调用

public class DefaultController : ControllerBase
{
    public Product GetProductStaticMethodinMyClassA(int Id)
    {
        return MyClassA.GetProduct(Id);
    }

    public Product GetProductStaticMethodinMyClassB(int Id)
    {
        return MyClassB.GetProduct(Id);
    }


    public Product GetProductinRequlurUse(int Id)
    {
        MyContext myContext = new MyContext();

        return myContext.Products.Where(x => x.Id == Id).SingleOrDefault();

    }
}

【问题讨论】:

  • 您想用MyClassAMyClassB 实现什么?如果你想封装DbContext,你可以考虑实现Repository而不是Static Method

标签: asp.net-mvc entity-framework-6 asp.net-core-mvc asp.net-core-webapi dbcontext


【解决方案1】:

您需要为每个 HTTP 请求创建一个 DbContext...即不要在多个请求之间共享相同的 DbContext。

C# 垃圾收集器会在 DbContext 超出范围后自动处理它,因此您不必将其放入 using 块中,但话虽如此,大多数人确实使用 using 块和MS seems to encourage it:

上下文的生命周期从创建实例开始,并且 当实例被处置或垃圾收集时结束。采用 如果您想要上下文控制的所有资源,请使用 设置在区块的末端。当你使用 using 时,编译器 自动创建一个 try/finally 块并调用 dispose 最后阻塞。

public void UseProducts()
{
    using (var context = new ProductContext())
    {     
        // Perform data access using the context
    }
}

关于在您的控制器中使用DbContext,您的问题是关于基于设计和意见的...如果您遵循 DDD 原则,DbContext 进入基础设施层并且您的控制器属于表示层...所以您会首先不要直接在控制器中使用DbContext

如果你想在控制器内部使用DbContext,最好注入它,而不是在控制器中初始化它,在控制器内部初始化DbContext违反SRP,因为初始化@987654332不是控制器的关注点@。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 2020-05-30
    • 2011-05-14
    • 1970-01-01
    • 2015-04-11
    • 2013-01-31
    • 2011-09-14
    • 1970-01-01
    相关资源
    最近更新 更多