我有这个查询
var query = from v in this._venueRepository.Table
join s in this._storeRepository.Table on v.VenueID equals s.VenueID
join w in this._workstationRepository.Table on s.StoreID equals w.StoreID
join t in this._tillSummaryRepository.Table on w.WorkstationID equals t.TillOpID
group new { v.DiscItemName_1, t.DiscItem_1, t.QDiscItem_1 } by new { v.DiscItemName_1 } into g
select new { Discount = g.Key, Amount = g.Sum(p => p.DiscItem_1), Qty = g.Sum(p => p.QDiscItem_1) };
我想执行此查询(可能是异步)但每次执行此查询时我都想更新参数“_1” - > “_2” - >例如“_3”等
var query = from v in this._venueRepository.Table
join s in this._storeRepository.Table on v.VenueID equals s.VenueID
join w in this._workstationRepository.Table on s.StoreID equals w.StoreID
join t in this._tillSummaryRepository.Table on w.WorkstationID equals t.TillOpID
group new { v.DiscItemName_2, t.DiscItem_2, t.QDiscItem_2 } by new { v.DiscItemName_2 } into g
select new { Discount = g.Key, Amount = g.Sum(p => p.DiscItem_2), Qty = g.Sum(p => p.QDiscItem_2) };
等等等我有什么想法可以做到这一点?也许反思?
答案 0 :(得分:1)
当你提到时,这样做的一种方式当然是反思。基于您的示例的示例如下:
var t = ._venueRepository.Table.FirstOrDefault().GetType();
for(int iterationCount = 1; iterationCount < MAX_ITERATIONS ; iterationCount++)
{
PropertyInfo itemNameProperty = t.GetProperty(String.Format("DiscItemName_{0}", iterationCount));
PropertyInfo discItermProperty = t.GetProperty(String.Format("DiscItem_{0}", iterationCount));
//Repeat the above for all properties.
var query = from v in this._venueRepository.Table
join s in this._storeRepository.Table on v.VenueID equals s.VenueID
join w in this._workstationRepository.Table on s.StoreID equals w.StoreID
join t in this._tillSummaryRepository.Table on w.WorkstationID equals t.TillOpID
//Repeat the below for other properties
group new { itemNameProperty.GetValue(v), dicItemProperty.GetValue(v) , qDiscProperty.GetValue(v) } by new { itemNameProperty.GetValue(v) } into g
//Similarly do for the select new.
select new { Discount = g.Key, Amount = g.Sum(p => p.DiscItem_1), Qty = g.Sum(p => p.QDiscItem_1) };
//Other code here.
}
如果您使用的是Entity框架,则上述查询将无效。这不起作用的原因是实体框架将尝试将您的查询转换为SQL,并且将在反射部分失败。您需要做的是将查询分成两部分。进行过滤并一步完成并将其检索到List,然后使用反射在另一个查询中创建匿名类型。但是,对于此操作,您将使用更多内存,并且您正在失去使用Linq to Entity的好处。