2013-01-25 56 views
2

我在if語句中定義了一個變量,然後嘗試在該語句的上下文之外使用該變量。如何在if語句之外初始化空的dbSet以便viewModel可以看到/填充它?初始化ASP.NET MVC中的空白dbSet 3

這就是我試圖完成:

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; 
}; 
+0

您正在使用您的查詢的.ToList()方法。你爲什麼不在if語句之外定義'IList filteredOrders'? – juanreyesv

回答

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; 
}; 
+0

非常感謝。我試過這個,我得到了.Where()子句的錯誤......任何想法爲什麼? – RobVious

+0

我的評論是指你的「更好的」解決方案 - 並且錯誤表示沒有支持過濾器的Where()方法。 – RobVious

+0

@RobVious:看起來我發現問題在哪裏,請參閱我的[最近更改](http://stackoverflow.com/posts/14513671/revisions)。 'Where()'[接受謂詞](http://msdn.microsoft.com/en-us/library/bb534803.aspx),即返回'bool'的泛型func。 – abatishchev