以下方案的最佳做法是什么:
我有一个LINQ to SQL表达式,在其投影中我想调用一个私有方法。 我知道我的方法无法转换为SQL,但我确实需要逻辑。 在获取查询结果后更改属性是不可能的,因为您无法更改投影属性(它是只读的)。
10倍
var projectedOrders = from order in orders
select new
{
orderId = order.Id,
orderName = order.FriendlyName,
OrderDate = order.OrderDate,
CustomerName = helper.GetUserNameByUserId(order.UserId)
};
答案 0 :(得分:4)
你必须分2步完成
var projectedOrders = (from order in orders
select new
{
orderId = order.Id,
orderName = order.FriendlyName,
OrderDate = order.OrderDate,
UserId= order.UserId
})
.ToArray()
.Select(o =>
new{
o.orderId,
o.orderName,
o.OrderDate,
CustomerName = helper.GetUserNameByUserId(o.UserId)
});
答案 1 :(得分:1)
您可以将UserId
临时存储到属性中并将CustomerNames
设置为 null ,然后在查询后使用循环并更改CustomerNames的值:
var projectedOrders = (from order in orders
select new
{
orderId = order.Id,
orderName = order.FriendlyName,
OrderDate = order.OrderDate,
UserId = order.UserId,
CustomerName = null
}).ToList();
foreach(var order in projectedOrders)
order.CustomerName = helper.GetUserNameByUserId(order.UserId);