将LINQ查询另存为变量以调用另一个LINQ查询 [英] Save LINQ Query As Variable To Call Another LINQ Query
问题描述
我有一个var类型,用于存储我想用作另一个LINQ查询的参数的LINQ查询的结果.
I have a var type storing the result of a LINQ query that I would like to use as a parameter for another LINQ query.
我正在使用控制器:
public async Task<ActionResult> Index(String aContainer)
{
var partsLocations = db.PartsLocations.Include(p => p.LocationType).Include(p => p.ManufacturingPlant);
var empty = from y in db.PartsLocations select y;
if (!String.IsNullOrEmpty(aContainer))
{
var parentLoc = from a in db.PartsLocations
where a.LocationName.Contains(aContainer)
select a.ParentLocation;
var location = (from b in db.PartsLocations.Where(b => parentLoc.Equals(b.LocationID))
select b).ToList();
return View( location.ToList());
}
empty = empty.Where(r => r.LocationName.Contains(null));
return View(await empty.ToListAsync());
}
我的看法是:
@model IEnumerable<Parts.PartsLocation>
@{
ViewBag.Title = "Index";
}
型号:
public int LocationID { get; set; }
public int TypeID { get; set; }
public string LocationName { get; set; }
public string Description { get; set; }
public int PlantID { get; set; }
public Nullable<int> BayID { get; set; }
public Nullable<int> SecurityGroupID { get; set; }
public Nullable<int> ParentLocation { get; set; }
public Nullable<System.DateTime> LastMoved { get; set; }
public string Notes { get; set; }
但是我收到错误消息:无法将类型'System.Int32'强制转换为'System.Object'.LINQto Entities仅支持强制转换EDM基本类型或枚举类型."
But I am getting error: "Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."
在SQL中,我做类似的事情:
In SQL I do something like:
从PartsLocations中的LocationName ='aContainer';
SELECT ParentLocation FROM PartsLocations where LocationName = 'aContainer';
选择* FROM PartsLocations,其中LocationID = ParentLocation;
SELECT * FROM PartsLocations where LocationID = ParentLocation;
如何将LINQ查询的结果用作单独查询的参数? 预先感谢!
How can I use the result of a LINQ query as a parameter for a separate query? Thanks in advance!
推荐答案
此
var parentLoc = from a in db.PartsLocations
where a.LocationName.Contains(aContainer)
select a.ParentLocation;
不是结果.这是一个查询.
is not a result. It is a query.
如果需要结果,请运行查询:
If you want a result, run the query:
var location = parentLoc.Single();
尝试,类似:
var parentLoc = (from a in db.PartsLocations
where a.LocationName == aContainer
select a.ParentLocation).Single();
var locations = (from b in db.PartsLocations
where b.LocationID == parentLoc
select b).ToList();
这篇关于将LINQ查询另存为变量以调用另一个LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!