Вы должны объединить две таблицы, а затем использовать агрегаты, чтобы получить все это в одном запросе, например:
var fruitCount = fruitSale
.Join(fruits, s => s.FruitId, f => f.FruitId, (s, f) => new {Sale = s, Fruit = f})
.GroupBy(g => g.Sale.FruitId)
.Select(s =>
new FruitsModel
{
FruitSaleId = s.First().Sale.FruitSaleId,
FruitId = s.Key,
FruitCount = s.Sum(x => x.Sale.Amount),
FruitName = s.First().Fruit.FruitName,
FruitType = s.First().Fruit.FruitType,
// FruitColor = s.First().Fruit.FruitColor
});
Для полного рабочего примера, извините, у меня нет вашей базы данных, поэтому я подделал это с некоторыми данными объекта
void Main()
{
// Some selected fruits to sell
var fruits = new List<Fruit> {
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Banana",
FruitType = "Tropical",
FruitColor = "Yellow"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Pineapple",
FruitType = "Tropical",
FruitColor = "Yellow"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Nectarine",
FruitType = "Stone",
FruitColor = "Red Yellow"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Apricot",
FruitType = "Stone",
FruitColor = "Yellow"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Peach",
FruitType = "Stone",
FruitColor = "Pinkish Yellow"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Plum",
FruitType = "Stone",
FruitColor = "Brownish Gray Purle"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Orange",
FruitType = "Citrus",
FruitColor = "Orange"
},
new Fruit {
FruitId = Guid.NewGuid(),
FruitName = "Lemon",
FruitType = "Citrus",
FruitColor = "Yellow"
}
};
// Generate some random fruit sales for each fruit
var random = new Random();
var fruitSale = new List<FruitSale>();
fruits.ForEach(f => fruitSale.Add(
new FruitSale {
FruitId = f.FruitId,
FruitSaleId = Guid.NewGuid(),
Amount = random.Next(1, 100)
}));
// Answer
var fruitCount = fruitSale
.Join(fruits, s => s.FruitId, f => f.FruitId, (s, f) => new {Sale = s, Fruit = f})
.GroupBy(g => g.Sale.FruitId)
.Select(s =>
new FruitsModel
{
FruitSaleId = s.First().Sale.FruitSaleId,
FruitId = s.Key,
FruitCount = s.Sum(x => x.Sale.Amount),
FruitName = s.First().Fruit.FruitName,
FruitType = s.First().Fruit.FruitType,
FruitColor = s.First().Fruit.FruitColor
})
.ToList();
fruitCount.ForEach(c => Console.WriteLine($"{c.FruitSaleId}, {c.FruitId}, {c.FruitCount}, {c.FruitName}, {c.FruitType}, {c.FruitColor}"));
}
public class FruitSale
{
public Guid FruitSaleId { get; set; }
public Guid FruitId { get; set; }
public int Amount { get; set; }
}
public class Fruit
{
public Guid FruitId { get; set; }
public string FruitName { get; set; }
public string FruitType { get; set; }
public string FruitColor { get; set; }
}
public class FruitsModel
{
public Guid FruitSaleId { get; set; }
public Guid FruitId { get; set; }
public int FruitCount { get; set; }
public string FruitName { get; set; }
public string FruitType { get; set; }
public string FruitColor { get; set; }
}