当需要的值来自数据库时,使用 LINQ 更新对象的 属性

Updating a property of an object using LINQ when value needed is from db

你认为我如何解决这个问题?基本上,我有这个初始查询:

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();

在此查询之后,我需要遍历结果并根据不同的条件更新类型 属性,如下所示:

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,但如果我必须遍历数百或数千条记录,然后 JOIN 每条记录,然后检查 db 只是为了获得一个值,我认为这会非常慢。

我无法对初始查询执行 JOIN,因为我可能会根据不同的条件执行不同的 JOIN。有什么想法吗?

您可以以左联接类型的方式联接您可能需要的所有查找表:

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