gpt4 book ai didi

c# - 在 ASP.NET MVC 3 中初始化一个空白的 dbSet

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:17 26 4
gpt4 key购买 nike

我在 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;
};

最佳答案

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

关于c# - 在 ASP.NET MVC 3 中初始化一个空白的 dbSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14513653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com