在ASP.NET MVC 3中初始化空白dbSet

时间:2013-01-25 00:57:59

标签: c# .net asp.net-mvc-3 linq

我在if语句中定义一个变量,然后尝试在该语句的上下文之外使用该变量。如何在if语句之外初始化空dbSet,以便viewModel可以查看/填充它?

这就是我想要完成的事情:

if (order.type.ToString() == "Rush")
{
    var filteredOrders = db.Orders.Where(a => a.rushID == order.rushID).ToList(); 
}
else if (order.type.ToString() == "Standard")
{
    var filteredOrders = db.Orders.Where(a => a.standardID == order.standardID).ToList();
}
else
{
    return HttpNotFound();
}

var viewModel = new OrderDetailsViewModel
{
    PastOrders = filteredOrders,  // filteredOrders doesn't exist here
    Order = order;
};

1 个答案:

答案 0 :(得分:1)

IEnumerable<Order> filteredOrders; // or IList<Order>, etc., as your prefer

switch (order.type.ToString())
{
    case "Rush":
        filteredOrders = db.Orders.Where(a => a.rushID == order.rushID).ToList();
    case "Standard":
        filteredOrders = db.Orders.Where(a => a.standardID == order.standardID).ToList();
    default::
        return HttpNotFound();
}

var viewModel = new OrderDetailsViewModel
{
    PastOrders = filteredOrders,
    Order = order;
};

或更好:

Func<Order, bool> filter;

switch (order.type.ToString())
{
    case "Rush":
        filter = a => a.rushID == order.rushID;
    case "Standard":
        filter = a => a.standardID == order.standardID;
    default::
        return HttpNotFound();
}

var viewModel = new OrderDetailsViewModel
{
    PastOrders = db.Orders.Where(filter).ToList(),
    Order = order;
};