我试图实例化一个自定义对象,该对象在数据库对象上向下钻取几个级别,并且我得到运行时数据库连接错误。
在我的控制器类......
private MyEntities db = new MyEntities();
...
foreach (Order thisOrder in orders) {
CustomerActionReturnModel thisAction = new CustomerActionReturnModel(thisOrder);
thisAction.Order.OrderItems = new List<OrderItemReturnModel>();
foreach (OrderItem thisItem in thisOrder.OrderItems) {
thisAction.Order.OrderItems.Add(new OrderItemReturnModel(thisItem));
}
thisResponse.CustomerActions.Add(thisAction);
}
...
protected override void Dispose(bool disposing) {
if (disposing) {
db.Dispose();
}
base.Dispose(disposing);
}
在我的模型课程中
...
[ModelName("OrderItemReturnModel")]
public class OrderItemReturnModel {
...
public OrderItemReturnModel(OrderItem dbOrderItem) {
OrderItemID = dbOrderItem.OrderItemID;
PriceCharged = dbOrderItem.PriceCharged;
if (dbOrderItem.Quantity != null) {
Quantity = (int)dbOrderItem.Quantity;
}
ProductDescription = dbOrderItem.StoreProduct.Product.Description;
ProductImageURL = dbOrderItem.StoreProduct.Product.ImageURLFormatted48;
}
如您所见,我尝试访问
dbOrderItem.StoreProduct.Product.Description;
和
dbOrderItem.StoreProduct.Product.ImageURLFormatted48;
它并不喜欢它
"Message": "An error has occurred.",
"ExceptionMessage": "ExecuteReader requires an open and available Connection. The connection's current state is closed.",
"ExceptionType": "System.InvalidOperationException"
在我构建OrderItemReturnModel时,有什么方法可以让我的dbContext保持打开状态?
答案 0 :(得分:-1)
我知道您使用的是ASP.NET,因为您在我的控制器中提到“,所以请不要使用控制器级的db上下文。
在像asp.net这样的多线程环境中执行此操作会引发许多问题。
建议的方法是在using语句中的任何位置创建DbContext的实例:
在您的控制器中(或者更好的是,在服务类,存储库或业务经理中):
using (var db = new MyEntities()){
//use db to fetch orders
foreach (Order thisOrder in orders) {
CustomerActionReturnModel thisAction = new CustomerActionReturnModel(thisOrder);
thisAction.Order.OrderItems = new List<OrderItemReturnModel>();
foreach (OrderItem thisItem in thisOrder.OrderItems) {
thisAction.Order.OrderItems.Add(new OrderItemReturnModel(thisItem));
}
thisResponse.CustomerActions.Add(thisAction);
}
}
DbContext被设计为短期对象,并将其声明为成员变量不会为您提供更好的性能,但相反。