你觉得我怎么解决这个问题?基本上,我有这个初始查询:
var orders = (from order in _dbContext.Orders
join orderDetail in _dbContext.OrderDetails on order.ID equals orderDetail.OrderID
where order.StoreID == storeID
select new Order
{
ID = order.ID,
No = order.ID,
Type = "", // Notice that this is empty; this one needs updating
Quantity = order.Quantity,
// more properties here
}).AsQueryable();
在此查询之后,我需要遍历结果并根据不同的标准更新Type属性,如下所示:
string type = "";
foreach (OrderDetailDto order in orders)
{
if (order.UserID != null)
type = "UserOrder";
else if (order.UserID == null)
type = "NonUserOrder";
else if (order.Cook == null && (order.Option == "fiery"))
type = "FieryCook";
else if (check if this has corresponding records in another table) // this part I don't know how to effectively tackle
type = "XXX";
// Update.
order.Type = type;
}
问题是我的标准之一需要我检查数据库中是否有现有记录。我会使用JOIN但是如果我必须循环通过几百或几千条记录然后加入它们中的每一条然后检查db只是为了获得一个值,我认为这将是非常慢的。
我无法在初始查询中执行JOIN,因为我可能会根据不同的条件执行不同的JOIN。有什么想法吗?
答案 0 :(得分:0)
您可以加入左连接类型方式可能需要的所有查找表:
from o in Orders
from c in Cooks.Where(x => x.OrderId == m.OrderId).DefaultIfEmpty()
from u in Users.Where(x => x.OrderId == o.OrderId).DefaultIfEmpty()
select new
{
Order = m,
Cook = c,
User = u
}
或者根据您的使用模式,您可以将所需的表构建到本地查找或词典中,以便以后进行线性时间搜索:
var userDict = Users.ToDictionary(x => x.UserId);
var userIdDict = Users.Select(x => x.UserId).ToDictionary(x => x);
var cooksLookup = Cooks.ToLookup(x => x.Salary);