每个请求的静态方法中的EntityFramework DbContext

问题描述 投票:0回答:1

实体框架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();

    }
}
asp.net-mvc entity-framework-6 asp.net-core-mvc asp.net-core-webapi dbcontext
1个回答
1
投票

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

C#垃圾收集器一旦超出范围就会自动处理DbContext,所以你不必把它放在using块中,但是说过,大多数人都使用using块和MS seems to encourage it

上下文的生命周期在创建实例时开始,在实例处理或垃圾收集时结束。如果您希望将上下文控制的所有资源放置在块的末尾,请使用。使用时,编译器会自动创建一个try / finally块,并在finally块中调用dispose。

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

关于DbContext在你的控制器中的用法,你的问题是基于设计和意见...如果你遵循DDD原则,DbContext进入基础设施层,你的控制器属于Presentation Layers ...所以你不会直接在控制器中使用DbContext在第一位。

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

© www.soinside.com 2019 - 2024. All rights reserved.