【发布时间】: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();
}
}
【问题讨论】:
-
您想用
MyClassA和MyClassB实现什么?如果你想封装DbContext,你可以考虑实现Repository而不是Static Method。
标签: asp.net-mvc entity-framework-6 asp.net-core-mvc asp.net-core-webapi dbcontext