public ActionResult ReadXMLDevices(int groupID)
{
var query = from k in XMLEntities.unassigneditems
where k.DevOrAcc == true && k.Group == groupID
select k;
var view_query = from i in query
select new GetFreeDevices
{
MArticleNumber = i.ArticleNumber,
MFirmware = i.Firmware,
MGroup = i.Group,
MName = i.Name,
MSoftware = i.SoftwareVersion,
SA = GetNumberOfDevices(i.ArticleNumber,2),
STH = GetNumberOfDevices(i.ArticleNumber,3),
SASTH = GetNumberOfDevices(i.ArticleNumber,7)
};
return PartialView(view_query);
}
public int GetNumberOfDevices(string artNo,int loc)
{
var num_dev = (from k in XMLEntities.deviceview
where k.Reserved == false && k.Sold == false && k.LocationNameId == loc && k.ArticleNumber == artNo
select k).Count();
return num_dev;
}
错误:
LINQ to Entities无法识别方法'Int32 GetNumberOfDevices(System.String,Int32)'方法,并且此方法无法转换为商店表达式。如何解决这个???
答案 0 :(得分:9)
您可以将查询拆分为两个,以确保在调用GetNumberOfDevices()
方法之前列表在内存中。您可以将结果转换为List
,或者在此情况下为List<GetFreeDevices>
,从而在内存中进行查询。这样,LinQ to Entities就不必对XML进行任何翻译,您可以使用GetNumberOfDevices()
方法。
var view_query = (from i in query
select new GetFreeDevices
{
MArticleNumber = i.ArticleNumber,
MFirmware = i.Firmware,
MGroup = i.Group,
MName = i.Name,
MSoftware = i.SoftwareVersion
}).ToList();
var result_query = from i in query
select new GetFreeDevices
{
MArticleNumber = i.MArticleNumber,
MFirmware = i.MFirmware,
MGroup = i.MGroup,
MName = i.MName,
MSoftware = i.MSoftware,
SA = GetNumberOfDevices(i.MArticleNumber,2),
STH = GetNumberOfDevices(i.MArticleNumber,3),
SASTH = GetNumberOfDevices(i.MArticleNumber,7)
};
return PartialView(result_query);
请注意,最后一条语句要求PartialView接受列表或IEnumerable
而不是IQueryable
。
答案 1 :(得分:0)
还有另一种简单的方法。
首先,将数据从数据库加载到内存:
// ...
var query_view = from i in query
select i;
query_view.Load();
// ...
然后,使用linq-to-objects做任何你想做的事情,而不是L2E:
var view_query_1 = from i in DbContext.myEntities.Local
select new GetFreeDevices
{
MArticleNumber = i.ArticleNumber,
MFirmware = i.Firmware,
MGroup = i.Group,
MName = i.Name,
MSoftware = i.SoftwareVersion,
SA = GetNumberOfDevices(i.ArticleNumber,2), //
STH = GetNumberOfDevices(i.ArticleNumber,3), // These are now ok!
SASTH = GetNumberOfDevices(i.ArticleNumber,7) //
};
return PartialView(view_query_1.AsEnumerable());
您可以将此技巧用于L2E不支持的任何方法。