在EF模型使用這些類兩個表涉及做組:Linq查詢,通過與不直接連接
class BoxOutput
{
public long BoxId { get; set; }
public virtual Box Box { get; set; }
public long BoxId { get; set; }
public long CategoryId { get; set; }
public virtual Category Category { get; set; }
public long? ColorId { get; set; }
public virtual Category Color { get; set; }
public decimal Weight { get; set; }
// ...and other irrelevant properties
}
class BoxInput
{
public long BoxId { get; set; }
public virtual Box Box { get; set; }
public long BoxId { get; set; }
public long CategoryId { get; set; }
public virtual Category Category { get; set; }
public long? ColorId { get; set; }
public virtual Category Color { get; set; }
public decimal Weight { get; set; }
// ...and other irrelevant properties
}
......我該怎麼辦LINQ查詢,對於一個特定的盒(如boxId = 12
),返回此?:
category.name color.name inputWeightsSum outputWeightsSum
---------------------------------------------------------------------------
c null 0 0
c red 0 0
c blue 0 0
m null 0 0
m red 0 0
m blue 0 0
....
我目前幾乎實現這一目標,但「可選顏色」是給做「笛卡爾積」當我的煩惱:我沒有顯示空。 ..
這就是我所擁有的。
var boxesInputs = dbContext.BoxesInputs
.Where(c => c.BoxId == 12)
.GroupBy(c => new { c.CategoryId, c.ColorId })
.Select(g => new
{
categoryId = g.Key.CategoryId,
colorId = g.Key.ColorId,
sumOfWeights = g.Sum(r => (decimal?)r.Weight) ?? 0,
}).ToList();
var boxesOutputs = dbContext.BoxesOutputs
.Where(c => c.BoxId == 12)
.GroupBy(c => new { c.CategoryId, c.ColorId })
.Select(g => new
{
categoryId = g.Key.CategoryId,
colorId = g.Key.ColorId,
sumOfWeights = g.Sum(r => (decimal?)r.Weight) ?? 0,
}).ToList();
var categoriesAndColors = dbContext.Categories.AsEnumerable()
.SelectMany(category => dbContext.Colors.AsEnumerable()
.Select(color => new
{
category = new
{
categoryId = category.CategoryId,
name = category.Name,
},
color = new
{
colorId = color.ColorId,
name = color.Name,
},
inputWeightsSum = boxesInputs.Where(r => r.categoryId == category.CategoryId && r.colorId == color.ColorId).Sum(r => (decimal?) r.sumOfWeights) ?? 0,
outputWeightsSum = boxesOutputs.Where(r => r.categoryId == category.CategoryId && r.colorId == color.ColorId).Sum(r => (decimal?)r.sumOfWeights) ?? 0,
})).ToList();
在上面的代碼中,前兩個查詢返回的:
category.name color.name inputWeightsSum
-------------------------------------------------------
c null 0
c red 0
c blue 0
m null 0
m red 0
m blue 0
....
category.name color.name outputWeightsSum
-------------------------------------------------------
c null 0
c red 0
c blue 0
m null 0
m red 0
m blue 0
....
,第三個加入這兩個。我想我需要改進這個連接,因爲我失去了空值。
另外,這段代碼使用內存中的代碼,我希望它是一個單一的sql查詢(linq-to-entities而不是linq-to-objects與linq-to-entities混合)。可能嗎?因爲BoxOutput和BoxInput是兩個不同的表格,它們不是直接相連的。不管怎樣,最終我最終會得到3個查詢?
我想我需要一個羣組加入 – sports 2014-11-21 21:35:24
你只是想得到一個笛卡爾產品? – paqogomez 2014-11-21 21:36:50
我的代碼的前兩個查詢被授予是正確的..我只是想將這兩個合併爲一個結果,按「(類別,顏色)」 – sports 2014-11-21 21:44:22