Entity Framework Many-To-Many + Count - c#

I have three tables, Professors, ProfessorStudent, Student.
I want all Professors + How many Students each Professor have.
I can do this:
context.ProfessorSet.Include("Student")
context.ProfessorSet.Include("Student").ToList() will read all three tables.
But i dont wanna get Student table, I want that Linq just get "Professor Table"+ "Count(*) ProfessorStudent Group By StudentId".
Its possible?

I do using this:
var c = from tag in contexto.ProfessorSet
select new
{
Tag = tag,
Count = tag.Student.Count
};
But generate this SQL:
SELECT
C.Id,
C.Nome,
C.C1
FROM
(SELECT
A.Id,
A.Nome,
(SELECT
COUNT(0)
FROM ProfessorStudant AS B
WHERE A.Id = B.ProfessorId
) AS [C1]
FROM Professor AS A)
I want this:
Select A.Id, Count(0) from Professor A
inner join ProfessorStudent B on A.Id = B.ProfessorId
Group By A.Id

from p in context.ProfessorSet
from s in p.Student
group s by s.StudentId into g
select new
{
Professor = p,
StudentCounts = from sc in g
select new
{
StudentId = sc.Key,
Count = sc.Group.Count()
}
}

Related

c# SQL Query error when trying to join a table

I am having diffculties joining a table in my code. Below you can see my code, I am getting an error on the join 2 table trying to connect my parts table.
if (query.Any()) // Check if REG is in the Database
{
int carID = query.FirstOrDefault().Id;
string carRegg = query.FirstOrDefault().regNo;
string carMake = query.FirstOrDefault().Make;
string carModel = query.FirstOrDefault().Model;
var test = (from a in dbC.Cars
where a.Id == carID
join b in dbC.Services on a.Id equals b.ServiceWrkNo
join c in dbC.PartsUseds on b.ServiceWrkNo equals c.PartsUsedNo
join d in dbC.Parts on c.PartsUsedNo equals d.PartName
select new
{
serviceNum = b.ServiceWrkNo,
PartNo = c.PartsUsedNo,
replacedParts = d.PartName
}).ToList();
the database I created from a model first method is below.
Your join do seems a little bit off -- could you try the join with the following columns
var test = (from a in dbC.Cars
where a.Id == carID
join b in dbC.Services on a.Id equals b.CarId
join c in dbC.PartsUseds on b.ServiceWrkNo equals c.ServiceServiceWrkNo
join d in dbC.Parts on c.PartsPartNo equals d.PartNo
select new
{
serviceNum = b.ServiceWrkNo,
PartNo = c.PartsUsedNo,
replacedParts = d.PartName
}).ToList();

Query entity select, inner join and count

i want to translate this SQL query :
SELECT FirstName,LastName, WaiterId, Count(*) AS compte
FROM Waiter
INNER JOIN Client on Waiter.Id = Client.WaiterId
GROUP BY WaiterId,lastname, firstname
ORDER BY compte DESC;
in entity framework.
I tried something like this :
var query = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
group c by c.WaiterId into g
//orderby
select new
{
WaiterId = g.Key,
count = g.Count()
});
but my select don't work. I can't select FirstName and LastName and i don't even know if my count is good.
You need to include all the properties in the group by.
var query = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
group c by new { c.FirstName, c.LastName, c.WaiterId} into g
orderby g.Count() descending
select new
{
FirstName = g.Key.FirstName,
LastName = g.Key.LastName,
WaiterId = g.Key.WaiterId,
count = g.Count()
});

convert group by query to linq

I am trying to convert below query in linq
select ta.id, ta.name, min(tb.id) from tableA ta
left join tableB tb on tb.fkid=ta.id
group by ta.id, ta.name
I tried below
var query = (from tableA in tableARepository.AsQueryable()
join tableB in tableBRepository.AsQueryable() on
tableA.Id equals tableB.fkid
group grp by new {tableA.Id, tableA.Name } into groupedCol
select new
{
Id = groupedCol.Key.Id,
Name = groupedCol.Key.Name,
fkId = grouppedCol.Min // cant get column fkid from tableB
}
);
I am not able to get Min of column fkid of tableB
What is missing here or how can i fix this?
You should be able to get the results that you are looking for without using Join or GroupBy:
var restrictTo = new[] {1, 2};
var query = tableARepository.AsQueryable()
// I want to add where clause like tableA.Id in (1,2)
.Where(a => restrictTo.Contains(a.Id))
.Select(a => new {
Id = a.Id
, Name = a.Name
, FkId = tableBRepository.AsQueryable().Min(b => b.fkid=a.id)
});
I think you are looking for GroupJoin
from tableA in tableARepository.AsQueryable()
join tableB in tableBRepository.AsQueryable() on
tableA.Id equals tableB.fkid into tb
select new
{
Id = tableA.Id,
Name = tableA.Name,
fkId = tb.Min(x => x.id)
}

ANDing in JOIN Condition Using LINQ

I recently ran into some SQL code that looks like this
SELECT
a.Id,
b.Id,
c.Id,
d.Id,
b.Name,
d.Occupation,
FROM TableA a
JOIN TableB b ON a.Id = b.Id
JOIN TableC c ON b.Id = c.Id AND b.Name = a.Name
JOIN tableD d ON c.Id = d.Id AND c.Occupation = d.Occupation
I've never used ANDs inside JOINs like this in a corresponding LINQ query (for context, I use the Entity Framework and LINQ for all of my queries). I usually put all my ANDs inside there where clause like this:
var query = from a in dbContext.TableA
join b in dbContext.TableB on a.Id equals b.Id
join c in dbContext.TableC on b.Id equals c.Id
join d in dbContext.TableD on c.Id equals d.Id
where b.Name = a.Name
where c.Occupation = d.Occupation
select new
{
AId = a.Id,
BId = b.Id,
CId = c.Id,
DId = d.Id,
BName = b.Name,
DOccupation = d.Occupation,
};
What technique can I use to get my LINQ query to match the SQL statement above?
You can join on multiple properties by constructing anonymous types from your properties like this:
var query = from a in dbContext.TableA
join b in dbContext.TableB on new { a.Id, a.Name } equals new { b.Id, b.Name }
join c in dbContext.TableC on b.Id equals c.Id
join d in dbContext.TableD on new { c.Id, c.Occupation } equals new { d.Id, d.Occupation }
select new
{
AId = a.Id,
BId = b.Id,
CId = c.Id,
DId = d.Id,
BName = b.Name,
DOccupation = d.Occupation,
};
Note that the name, order, and datatype of each property in the anonymous types need to be the same on both sides of the equals in order for this to work. Otherwise they would be two different anonymous types and would not be equatable.

How do I change this query to linq to sql?

Query:
select emp.empname as Name, dep.depname as Department
from Employee as emp
inner join Department as dep on emp.depid=dep.depid
where emp.id='2'
How can I change this to linq to sql?
var id = 2;
var qry = from e in db.Employees
where e.Id == id
select new {
Name = e.EmpName,
Department = e.Department.DepName
};
(assumes the parent-association between employee and department is defined in the DBML)
and if you expect exactly one such:
var record = qry.Single();
Console.WriteLine(record.Name);
Console.WriteLine(record.Department);
Approximately:
from e in dc.Employee
join d in dc.Department on e.depid equals d.depid
where e.id == '2'
select new
{
Name = e.empname,
Department = d.depname
}
This is why LINQ is so great: there is no reason to even join with the Departments table to get it to work:
from employee in db.Employees
where employee.id == 2
select new
{
Name = employee.empname,
Department = employee.Department.depname
};

Categories

Resources