[英]Merging data from two tables into one view
我在将来自两个不同表的数据合并到一个视图时遇到了一些麻烦。 如果您知道该怎么做,请告诉我。 这就是我正在使用的:
我有四个表:
public class CoinAllocation
{
public int CoinAllocationID { get; set; }
public int? StoreID { get; set; }
public int? TimeFrameID { get; set; }
public virtual Store Store { get; set; }
public virtual TimeFrame TimeFrame { get; set; }
public virtual List<CoinAllocationItem> CoinAllocationItems { get; set; }
}
public class CoinAllocationItem
{
public int CoinAllocationItemID { get; set; }
public int? CoinID { get; set; }
public int? StoreID { get; set; }
public int? CoinAllocationID { get; set; }
public int QuantityAllocated { get; set; }
public virtual Coin Coin { get; set; }
}
public class CoinUsed
{
public int CoinUsedID { get; set; }
public int? TimeFrameID { get; set; }
public int? StoreID { get; set; }
public virtual Store Store { get; set; }
public virtual TimeFrame TimeFrame { get; set; }
public virtual List<CoinUsedItem> CoinUsedItems { get; set; }
}
public class CoinUsedItem
{
public int CoinUsedItemID { get; set; }
public int? CoinUsedID { get; set; }
public int? CoinID { get; set; }
public int? QuantityUsed { get; set; }
public virtual Coin Coin { get; set; }
public int? StoreID { get; set; }
}
现在,我需要遍历这些表以查找来自同一商店和相同时间范围的硬币。 然后,我需要组合具有相同ID的硬币,总计它们的分配数量,然后总计它们已使用的数量。 最后,我需要将它们置于一个像这样设置的视图中:
Coin Name | Amount Allocated | Amount Used | Remaining
silver coin 10 1 9
gold coin 15 5 10
等等...
因此,如果在同一时间段内同一家商店有两枚银币,它们将在表中仅一行显示,并显示总数。
我遇到的问题是从一个表中获取分配,并从另一表中获取使用。
任何可以提供帮助的人都会很棒。
通常,您必须考虑以下步骤:
Where
) Select
和SelectMany
) GroupBy
) Join
和GroupJoin
) 总是有不止一种方法。 我想在某个时候使用GroupJoin
可能比我目前想出的效率更高,如果您从Coin
开始而不是分别处理CoinAllocation
和CoinUsed
,则可能会获得更好的结构化代码,具体取决于可用的导航属性...
以下是我提出的内容,可能满足或可能不满足您的需求-您提出的模型和标准存在一些不确定性。
// whatever you search for... this assumes you want coins for one store in one timeframe
int desiredStoreID = 0, desiredTimeFrameID = 0;
var coinUsedSelection = db.CoinUsed
.Where(x => x.StoreID == desiredStoreID && x.TimeFrameID == desiredTimeFrameID)
.SelectMany(x => x.CoinUsedItems)
.GroupBy(x => x.CoinID, x => x.QuantityUsed, (k, v) => new { CoinID = k, QuantityUsedSum = v.Sum() });
var coinAllocationSelection = db.CoinAllocations
.Where(x => x.StoreID == desiredStoreID && x.TimeFrameID == desiredTimeFrameID)
.SelectMany(x => x.CoinAllocationItems)
.GroupBy(x => new { x.CoinID, x.Coin.CoinName }, x => x.QuantityAllocated, (k, v) => new { k.CoinID, k.CoinName, QuantityAllocatedSum = v.Sum() });
var result = coinAllocationSelection.Join(coinUsedSelection, ca => ca.CoinID, cu => cu.CoinID, (ca, cu) => new
{
CoinName = ca.CoinName,
AmountAllocated = ca.QuantityAllocatedSum,
AmountUsed = cu.QuantityUsedSum,
Remaining = ca.QuantityAllocatedSum - cu.QuantityUsedSum
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.