我有以下代码:
ServiceSoapClient service = new ServiceSoapClient();
var dataSource = (from u in _db.Sessions
where u.DeletedOn == null
select new
{
SessionId = u.UploadSessionId,
FileName = u.FileName,
CreatedBy = u.User.UserName,
Partner = u.Company.Name,
CreatedOn = u.CreatedOn,
Visible = service.IsSessionProcessing(u.UploadSessionId)
})
.OrderByDescending(x => x.CreatedOn);
...当然这里的问题是Visible = service.IsSessionProcessing(u.UploadSessionId)
部分有权访问修改后的闭包,因为当我在某处使用dataSource
,即预成型.ToList()
或类似的东西时实际计算表达式
这里的问题是我无法立即执行.ToList()
,因为我需要将其用作控件的数据源。
Linq有什么方法可以避免这种情况吗?我可以在表达式中使用局部变量,以便使用实际值计算它吗?
答案 0 :(得分:1)
这里的“修改后的闭包”是service
。所以...不要重新分配service
。
答案 1 :(得分:0)
真正的错误在于尝试在表达式的上下文中调用函数,这对于表示数据库操作的表达式没有任何意义。 我想你实际上尝试了以下内容:
// Database operation, no soap client funny business here.
var list = (
from u in _db.Sessions
where u.DeletedOn == null
orderby x.CreatedOn descending
select new
{
SessionId = u.UploadSessionId,
FileName = u.FileName,
CreatedBy = u.User.UserName,
Partner = u.Company.Name,
CreatedOn = u.CreatedOn,
}).ToList();
// From now on you are not in a database anymore, it's pure linq-to-objects. You can call the service.
ServiceSoapClient service = new ServiceSoapClient();
var dataSource = (from u in list select new {
SessionId = u.SessionId,
FileName = u.FileName,
CreatedBy = u.CreatedBy,
Partner = u.Partner,
CreatedOn = u.CreatedOn,
Visible = service.IsSessionProcessing(u.SessionId)
}).ToList();