问题描述
当尝试传递从列表对象获取的列值时,Linq查询返回null。是否可以做在代码中做。期望的答案或一些建议。
Linq query returning null when trying to pass a column value fetched from list objects . Is it possible to do as done in the code. Expecting answer or some suggestion.
var query = from p in context.ProcessStepTables
where (p.DiagramID == diagramInfo.DiagramID)
orderby p.ProcessNo select new{
DiagramProcessID = p.DiagramProcessID,
ProcessNo = p.ProcessNo,
ProcessID = p.ProcessID,
ProcessName = Process().Find(x =>
p.ProcessID == x.ProcessID).ProcessName.ToString(),
MakerName = Maker().Find(x=>
p.MakerID==x.MakerID).MakerName.ToString(),
Price = p.Price,
Note = p.Note,
Notice = p.Notice
};
private List<MakerTable> Maker()
{
List<MakerTable> pList = new List<MakerTable>();
try
{
IQueryable<MakerTable> maker = (from data in context.MakerTables
select data) as IQueryable<MakerTable>;
foreach (MakerTable val in maker)
{
pList.Add(val);
}
return pList.OrderBy(x => x.MakerName).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
推荐答案
是因为,你的提供者不知道 .ToString()
方法,即,当你创建一个IQueryable形式的查询,它被翻译成等价的SQL查询,所以如果你包括任何C#函数,事件一个非原始数据类型,它会抛出你的错误,因为你的查询被构造如下:
that is because, your provider doesn't know about .ToString()
method i.e., when you create a query in IQueryable form, it is translated into equivalent SQL query, so if you include any C# function, event a non-primitive datatype, it will throw you that error, because your query gets constructed something like below:
"Select s.DiagramProcessID as DiagramProcessID, ...other fields..
from MakerTables s where something.ToString()=='anyvalue'"
很明显,sql不知道任何关于 .ToString()
。
so obviously, sql doesn't know anything about .ToString()
.
简单的方法,避免是,在应用 .ToList()
到您的查询后,执行您的自定义选择。
Simply way to avoid is to, perform your custom Select, after applying .ToList()
to your query.
当你这样做或 .AsEnumerable()
时,查询在数据库上执行,现在无论什么自定义选择或where子句,在CLR上
When you do that or .AsEnumerable()
, query is executed on the database and now whatever custom selection or where clause is there, is translated on the CLR
请尝试:
var query = context.ProcessStepTables
.Where(s=>s.DiagramID == diagramInfo.DiagramID)
.OrderBy(s=>s.ProcessNo)
.ToList() //this will cause the query to be executed on the db
//Now perform the selection on returned result set, now the linq
//has to do with this dataset
.Select(s=>new
{
DiagramProcessID = s.DiagramProcessID,
ProcessNo = s.ProcessNo,
ProcessID = s.ProcessID,
//other items in your custom list
});
,您也可以用以下替换您的Maker方法:
and also you can replace your Maker method with below:
private List<MakerTable> Maker()
{
try
{
return context.MakerTables.OrderBy(x=>x.MakerName).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
这篇关于当尝试从列表对象传递列值时,Linq查询返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!