multiple JOIN + SUM() query in LINQ -> can't loop in view - linq

I'm trying to translate an SQL query into LINQ, but after numerous attempts, I'm still not there... Can anyone help ?
This is my working SQL statement
SELECT Users.email, SUM(Skills.level) AS SkillLevel
FROM Skills INNER JOIN
SkillsPerUser ON Skills.pk_skill_id = SkillsPerUser.fk_skill_id INNER JOIN
Users ON SkillsPerUser.fk_user_id = Users.pk_userid
GROUP BY Users.email
ORDER BY SkillLevel DESC
This is what I came up with so far, but it lacks a sum() where I hard coded the number 3, that should be the sum of Skills.level:
var allSkillsPerUser = from u in dc.Users
join spu in dc.SkillsPerUsers on u.pk_userid equals spu.fk_user_id
join s in dc.Skills on spu.fk_skill_id equals s.pk_skill_id
select new { Email = u.email, Level = s.level } into su
group su by su.Email into gsu
select new { Email = gsu.Key, SkillLevel = gsu.Sum(su => su.Level) };
ViewBag.spu = allSkillsPerUser.ToList();
The view bag gives the following error (Email can't be found, while in the variables below you can see that they do exist...):

context.Skills
.Join(context.SkillsPerUser, s => s.pk_skill_id, spu => spu.fk_skill_id, (s, spu) => new { Skill = s, SkillToUser = spu })
.Join(context.Users, sspu => sspu.SkillToUser.fk_userId, u => u.pk_userid, (sspu, u) => new { Email = u.Email, SkillLevel = sspu.Skill.level })
.GroupBy(su => su.Email)
.Select(g => new { Email = g.Key, SkillLevel= g.Sum(su => su.Level) })
.OrderByDescending(g => g.SkillLevel)
It's a bit simpler if you have navigation properties set up on your entities:
context.SkillsPerUser
.Select(spu => new { Email = spu.User.email, Level = spu.Skill.level }) // guessing at the navigation property names here
.GroupBy(su => su.Email)
.Select(g => new { Email = g.Key, SkillLevel = g.Sum(su => su.Level) })
.OrderByDescending(g => g.SkillLevel)
Or, using the query syntax
from u in dc.Users
join spu in dc.SkillsPerUsers on u.pk_userid equals spu.fk_user_id
join s in dc.Skills on spu.fk_skill_id equals s.pk_skill_id
select new { Email = u.email, Level = s.level } into su
group su by su.Email into gsu
select new { Email = gsu.Key, SkillLevel = gsu.Sum(su => su.Level) }
To order by the sum you can do this:
from u in dc.Users
join spu in dc.SkillsPerUsers on u.pk_userid equals spu.fk_user_id
join s in dc.Skills on spu.fk_skill_id equals s.pk_skill_id
select new { Email = u.email, Level = s.level } into su
group su by su.Email into gsu
select new { Email = gsu.Key, SkillLevel = gsu.Sum(su => su.Level) } into userSkills
orderby userSkills.SkillLevel descending

Related

.net core linq select overload index does not work

I got a linq lambda select code that works before I added the Select index overload. Before, I got the list of records but I need the index which I use to assign a unique Id to each record. When I add with ToList(), I get an exception with no error/inner exception. Only way I can get the code to not throw an error is to use .AsEnumberable() but I need a list. I read many post that .ToList() works with the overload but I have been unsuccessful.
Here is my code and my attempt to fix this
var emps = this.DbContext.Employees
.GroupJoin(this.DbContext.Depts,
employee => employee.EmployeeId,
dept => dept.EmployeeId,
(employee, dept) => new { employee, dept }
)
.SelectMany(
employee_dept_left => employee_dept_left.dept.DefaultIfEmpty(),
(employee_dept_left, dept) => new { employee_dept_left, dept }
)
.Join(this.DbContext.Divs,
emp_emp_dept => emp_emp_dept.employee_dept_left.employee.DivId,
division => division.DivId,
(emp_emp_dept, division) => new { emp_emp_dept, division }
)
.Where(s => !string.IsNullOrEmpty(filter.selectedDiv))
.GroupBy(grouped => new
{
grouped.emp_emp_dept.employee_dept_left.employee.EmployeeId,
grouped.emp_emp_dept.employee_dept_left.employee.LastNm,
grouped.emp_emp_dept.employee_dept_left.employee.FirstNm,
grouped.emp_emp_dept.employee_dept_left.employee.DivId
})
.Select((joined, index) => new EmployeeViewModel
{
Id = index,
EmployeeId = joined.Key.EmployeeId,
LastNm = joined.Key.LastNm.Trim(),
FirstNm = joined.Key.FirstNm.Trim(),
DivisionId = joined.Key.DivId,
}).ToList();
The error message says
Could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
I tried using .AsEnumerable() instead of .ToList():
List<EmployeeViewModel> test = emps.Cast<EmployeeViewModel>().ToList();
but this throws an exception.
Any help is greatly appreciated.
Thanks in advance
Problem that this Select is not currently translatable to the SQL. You can make additional Select to solve issue with AsEnumerable().
...
.Select(joined => new
{
EmployeeId = joined.Key.EmployeeId,
LastNm = joined.Key.LastNm.Trim(),
FirstNm = joined.Key.FirstNm.Trim(),
DivisionId = joined.Key.DivisionId,
})
.AsEnumerable()
.Select((x, index) => new EmployeeViewModel
{
Id = index,
EmployeeId = x.EmployeeId,
LastNm = x.LastNm,
FirstNm = x.FirstNm,
DivisionId = x.DivisionId,
}).ToList();
And note that query is more readable in Query syntax when there are joins.
var query =
from employee in this.DbTracsContext.Employees
join dept in his.DbTracsContext.Depts on employee.EmployeeId equals dept.EmployeeId into employee_dept_left
from dept in employee_dept_left.DefaultIfEmpty()
join division in this.DbTracsContext.Depts on employee.DivisionId equals division.DivisionId
where string.IsNullOrEmpty(filter.DivisionSelection) || filter.DivisionSelection == "0" || employee.DivisionId == filter.DivisionSelection
group employee by new { employee.EmployeeId, employee.LastNm, employee.FirstNm, employee.DivisionId } into g
select new
{
EmployeeId = g.Key.EmployeeId,
LastNm = g.Key.LastNm.Trim(),
FirstNm = g.Key.FirstNm.Trim(),
DivisionId = g.Key.DivisionId,
};
var emps = query
.AsEnumerable()
.Select((x, index) => new EmployeeViewModel
{
Id = index,
EmployeeId = x.EmployeeId,
LastNm = x.LastNm,
FirstNm = x.FirstNm,
DivisionId = x.DivisionId,
}).ToList();

Linq use value from select new to calculate another field

Is it possible to do the following in linq, where in my select new I use the value from TotalOrderItems as part of the calculation for TotalInStockItems?
var Order = (from o in orderItems
select new ShippingOrder { OrderId = orderItems.OrderId
TotalOrderItems = orderItems.GroupBy(x => x.Sku).Count(),
TotalInStockItems = TotalOrderItems - orderItems.Where(x => x.InStock =='F').GroupBy(x => x.Sku).Count(),
}).ToList();
try using the let clause (C# Reference) to store the value for use later in the query
(from o in orderItems
let totalOrderItems = orderItems.GroupBy(x => x.Sku).Count()
select new ShippingOrder {
OrderId = o.OrderId
TotalOrderItems = totalOrderItems,
TotalInStockItems = totalOrderItems - orderItems.Where(x => x.InStock =='F').GroupBy(x => x.Sku).Count(),
}).ToList();

linq query crossjoin groupby optimize

i have the following database-model: http://i.stack.imgur.com/gRtMD.png
the many to many relations for Kunde_Geraet/Kunde_Anwendung are in explicit Mapping-Table with additional Information.
i want to optimize the following LINQ-query:
var qkga = (from es in db.Eintrag_Systeme.Where(es => es.Eintrag_ID == id)
from kg in db.Kunde_Geraet.Where(kg => es.Geraet_ID == kg.Geraet_ID)
select new { Kunde = kg.Kunde, Geraet = es.Geraet, Anwendung = es.Anwendung })
.Union(
from es in db.Eintrag_Systeme.Where(es => es.Eintrag_ID == id)
from ka in db.Kunde_Anwendung.Where(ka => es.Anwendung_ID == ka.Anwendung_ID)
select new { Kunde = ka.Kunde, Geraet = es.Geraet, Anwendung = es.Anwendung })
.GroupBy(kga => kga.Kunde, kga => new {Geraet = kga.Geraet, Anwendung = kga.Anwendung});
it would be better, when the result is a IEnumerable(Kunde, IEnumerable(Geraet), IEnumerable(Anwendung)) without the null-Values for the union.
i try it as SQL command
select Count(es.Geraet_ID), null as Anwendung_ID
from Eintrag_Systeme es cross join Kunde_Geraet where es.Geraet_ID = Kunde_Geraet.Geraet_ID AND es.Eintrag_ID = #id
union
select null as Geraet_ID, Count(es.Anwendung_ID)
from Eintrag_Systeme es cross join Kunde_Anwendung where es.Anwendung_ID = Kunde_Anwendung.Anwendung_ID AND es.Eintrag_ID = #id
group by Kunde_ID
but donĀ“t get the Count() of Anwendungen(Apps)/Geraete(Devices) to Lists grouped by Key Kunde(Client)
Don't use join but navigation properties:
from k in context.Kunden
select new
{
Kunde = k,
Geraete = k.Kunde_Geraete.Select(kg => kg.Geraet),
Anwendungen = k.Kunde_Anwendungen.Select(ka => ka.Anwendung)
}
Now you have a basis from which you get counts, etc.

Nested query with Join in LINQ expression

select DL.lat,
DL.lng,
DL.speed,
DL.trackedOn,
IL.speedLimit,
IL.deviceName,
IL.deviceId,
isnull(DeviceIcon, 'Content/images/beach-car.png') as DeviceIcon
from tb_DeviceLog DL
inner join (select inventoryLogId, max(trackedOn) as MaxDate
from tb_DeviceLog
group by inventoryLogId) IDL
on DL.inventoryLogId = IDL.inventoryLogId and Dl.trackedOn = IDL.MaxDate
inner join tb_InventoryLog IL
on DL.inventorylogid = IL.id
inner join tb_Logins LGN
on LGN.customers_id = IL.assignedToCustId
where LGN.userName='cadmin'
I need a lambda expression for the above query.
So far I have tried:
var query = db.tb_DeviceLog.Join(db.tb_DeviceLog, DL=>DL.inventoryLogId, DL1=>DL1.inventoryLogId, (DL,DL1)=> new{ DL1.inventoryLogId, DL1.trackedOn.Value}).GroupBy(a=>a.inventoryLogId)
But this is half of the result I want.
almost complex, i like that...
you need this:
var dbContext = new TestEntities();
dbContext.tb_DeviceLog
.Join(dbContext.tb_DeviceLog
.GroupBy(u => u.inventoryLogId)
.Select(u => new { inventoryLogId = u.Key, MaxDate = u.Max(t => t.trackedOn)}),
u => new { inventoryLogId = u.inventoryLogId, date = u.trackedOn},
u => new { inventoryLogId = u.inventoryLogId, date = u.MaxDate},
(DL , IDL) => new {DL, IDL})
.Join(dbContext.tb_InventoryLog,
u => u.DL.inventoryLogId,
u => u.id
(u, IL) => new { u.DL, u.IDL, IL })
.Join(dbContext.tb_Logins,
u => u.IL.assignedToCustId,
u => u.customers_id
(u, LGN) => new { u.DL, u.IDL, u.IL, LGN })
.Where(u => u.LGN.userName == "cadmin")
.Select(u => new
{
u.DL.lat,
u.DL.lng,
u.DL.speed,
u.DL.trackedOn,
u.IL.speedLimit,
u.IL.deviceName,
u.IL.deviceId,
// i don't know exactly, which table is containing this 'DeviceIcon', probably DL
u.DL.DeviceIcon == null ? "Content/images/beach-car.png" : u.DL.DeviceIcon
})
.ToList();

Simple Examples of joining 2 and 3 table using lambda expression

Can anyone show me two simple examples of joining 2 and 3 tables using LAMBDA EXPRESSION(
for example using Northwind tables (Orders,CustomerID,EmployeeID)?
Code for joining 3 tables is:
var list = dc.Orders.
Join(dc.Order_Details,
o => o.OrderID, od => od.OrderID,
(o, od) => new
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
ShipName = o.ShipName,
Quantity = od.Quantity,
UnitPrice = od.UnitPrice,
ProductID = od.ProductID
}).Join(dc.Products,
a => a.ProductID, p => p.ProductID,
(a, p) => new
{
OrderID = a.OrderID,
OrderDate = a.OrderDate,
ShipName = a.ShipName,
Quantity = a.Quantity,
UnitPrice = a.UnitPrice,
ProductName = p.ProductName
});
Thanks
try this one to join 2 tables using lambda expression
var list = dataModel.Customers
.Join( dataModel.Orders,
c => c.Id,
o => o.CustomerId,
(c, o) => new
{
CustomerId = c.Id,
CustomerFirstName = c.Firstname,
OrderNumber = o.Number
});
public void Linq102()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
}

Resources