I'm trying to get all students last attended class from database. I wrote tsql code and it works very well howevery i couldn't do the same on entityframework core.
This code below works for me.
select a.student, b.class, b.attend from students a inner join class b on b.id = (
select top 1 id
from class
where student = a.student order by attend desc
)
Also this is my attemp on writing EF query.
datavalue = db.students.join(
db.class, m => m.student,
s => s.student, (m, s) => new joinedstudentswclass { class = s.class, student = m.student }
).tolist();
u should use firstOrDefault to get a single record.
if u wanna order something, you should be used orderBy methods.
.OrderBy(x => x.City) for ascending students
.OrderByDescending(x => x.City) for descending students
the code should be something like
OrderByDescending(x=>x.Students).FirstOrDefault();
Without navigation properties:
var query =
from s in db.students
from c in db.Where(c => c.student == s.student).OrderByDescending(c => c.attend).Take(1)
select new joinedstudentswclass
{
class = c,
student = s
};
var datavalue = query.ToList()
If you have navigation property Classes in student class:
var query =
from s in db.students
from c in s.Classes.OrderByDescending(c => c.attend).Take(1)
select new joinedstudentswclass
{
class = c,
student = s
};
var datavalue = query.ToList()
Related
hi I'm using the query below to select studentId and Score from table1 now i want select users that i selected their ids from table2, how i can select it with ids?
i can select users with this query from v in dc.tbl_Students select v but i want select some users that i have their id.
var qBestMan = (from T in (((from tbl_ActPoints in dc.tbl_ActPoints
select new
{
StudentId = (int?)tbl_ActPoints.StudentId,
Score = (int?)tbl_ActPoints.Score
}).Concat(
from tbl_EvaPoints in dc.tbl_EvaPoints
select new
{
StudentId = (int?)tbl_EvaPoints.StudentId,
Score = (int?)tbl_EvaPoints.Score
})))
group T by new
{
T.StudentId
} into g
orderby g.Sum(p => p.Score) descending
select new
{
g.Key.StudentId,
HighScoreUser = g.Sum(p => p.Score)
}).ToArray();
Try something like this:
//qBestMan must be a List, or a IEnumarable and not a Array. Remove the .ToArray() at the end, or substitute it by .ToList()
var Result = from users in dc.tbl_Students
join bestMen in qBestMan on bestMen.StudentId equals users.userid
select new
{
//fields that you want
example = users.example,
other = bestMen.other
};
I have a function as below :
IEnumerable<Group> GetAllChildren(int parentID)
{
using (Entities db = new Entities())
{
var result = (from x in db.Groups
where x.ParentID == parentID
select x).ToList();
foreach (Group child in result.ToList())
{
result.AddRange(GetAllChildren(child.GroupID));
}
return result;
}
}
In the above function if I pass a group name I get all the children at all levels.
It works as expected.
Now my query looks like something like :
GroupNamesWithCorrespondingEffects
= new ObservableCollection<GroupNameWithCorrespondingEffect>
(from g in db.Groups
select new GroupNameWithCorrespondingEffect
{
GroupID = g.GroupID,
GroupName = g.GroupName,
CorrespondingEffect = g.Master_Effects.Effect
}
);
The above query will give me all the groups.
Now I want to remove all the groups from GroupNamesWithCorrespondingEffects that are children of a group with id == 25.
I have tried .Remove(GetAllChildren(25)) in 2nd query. but I get following error.
Collection.Remove(GroupNameWithCorrespondingEffect) has some invalid arguments.
hope this help you:
var childs = GetAllChildren(25).ToList();
var childIDList = childs.select(u => u.GroupID).ToList();
GroupNamesWithCorrespondingEffects = GroupNamesWithCorrespondingEffects
.Where(u => !childIDList.Contains(u.GroupID)).ToList();
I am new to nHibernate. I have following SQL inner join query,
SELECT e.name,
d.deptname
FROM demo_employee AS e
INNER JOIN demo_department AS d
ON e.departmentid = d.deptid
What is the linq expression using Query Over of the following sql query.
I have written the following query but it is qiving me error at following place "c.Department.DeptId".
var Query =
Session.QueryOver<Employee>()
.JoinQueryOver<Department>(c => c.Department.DeptId)
.Where(k => k.Name == k.DeptId);
Here is the QueryOver version.
We are using aliasing, ie: Declaration of the null reference Employee employee = null to be used for fully-typed access to all properties. NHibernate Expression parser will convert them into strings (column names) later based on mapping.
Also we could get references to FROM parts of the QueryOver. The query represents Employee, and the joined query represents the Department (depQuery), which we can directly filter.
Finally we can use List() to get (SELECT) all mapped properties, or do some projection: .Select() or .SelectList(). With projection, we should be working with some DTO.
// aliasing, see the Projections of the SELECT clause
Employee employee = null;
Department department = null;
// the Employee query, with alias
var query = session.QueryOver<Employee>(() => employee);
// this way we can have reference to department query, if needed
var depQuery = query.JoinQueryOver<Department>(() => employee.Department, () => department);
// WHERE
// filtering the Employee
query.Where(e => e.Name == "Undefined");
// the department filtering
depQuery.Where(d => d.DeptName == "Management");
// paging, if needed
query.Skip(100);
query.Take(10);
1) select all properties
var list = query.List<Employee>();
var employeeName = list.ElementAt(0).Name;
var departmentName = list.ElementAt(0).Department.DeptName;
2) projection
// The DTO class to be projected into
public class MyDTO
{
public virtual string EmployeeName { get; set; }
public virtual string DepartmentName { get; set; }
}
// Select with projection of just two columns
MyDTO dto = null;
// SELECT
// projection, explicit property/column to be selected only
query.SelectList(l => l
// the full power of aliasing
.Select(() => employee.Name).WithAlias(() => dto.EmployeeName)
.Select(() => department.DeptName).WithAlias(() => dto.DepartmentName)
);
var list = query
.TransformUsing(Transformers.AliasToBean<MyDTO>())
.List<MyDTO>();
I have a Table(Send) with columns(Id, UserId,SendDate) and another table(Receive) with columns(Id,SendId,UserName).
I want show all records in SendTable with all RecieveUserName.
for example.
(Send)
1 1 2013
2 2 2013
(Recieve)
1 1 Jack
2 1 Ema
3 2 Alex
4 2 Sara
Result
1 1 2013 Jack, Ema
2 2 2013 Alex, Sara
I use this query in SqlServer (The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement)
SELECT DISTINCT c2.Id,
(SELECT STR( UserName )+ ','
FROM dbo.Reciver c1
WHERE c1.SendId = c2.id FOR XML PATH('')) Concatenated, c2.SendDate, c2.UserId
FROM dbo.Send AS c2 INNER JOIN
dbo.Reciver ON c2.Id = dbo.Reciver.SendId
How do this query in Linq?
Distinct is also available in LINQ.
For example
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 10 },
new Product { Name = "lemon", Code = 9 } };
var lstDistProduct = products.Distinct();
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}
Will return all rows.
var list1 = products.DistinctBy(x=> x.Code);
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}
will return 9 and 4
It doesn't seem to me that you need to use Distinct in this Linq query. Assuming you have the relationships between tables set up on your linq datacontext, you can do something like this:
var result = from s in context.Send
select new {
id = s.Id,
userId = s.UserId,
date = s.SendDate,
users = s.Receive.Select(u => u.UserName)
}
Note: users will an IEnumerable<String> - you can use string.Join() on the client to join the names into a string.
Update
To return users as a string to first need to 'switch' to Linq To Objects by calling AsEnumerable() or ToList() and the Linq to Sql query.
var output = from s in result.AsEnumerable()
select new {
id = s.id,
userId = s.userId,
date = s.date,
users = string.Join(", ", s.users)
}
Also see Gert Arnolds answer for a good explanation.
What you want can only be done in two steps. Not because of the DISTINCT, but because of the FOR XML. The C# equivalent of the latter is String.Join(), but you can't use that in a linq to entities statement directly. So you must collect the required data first, then switch to linq to objects (by applying AsEnumerable) and then do the concatenation and distinct:
db.Sends
.Where(s => s.Receivers.Any())
.Select(s => new {
s.Id,
Concatenated = s.Receivers.Select(r => r.UserName)
s.SendDate,
s.UserId
})
.AsEnumerable()
.Select(x => new {
s.Id,
Concatenated = String.Join(", ", x.Concatenated)
s.SendDate,
s.UserId
})
.Distinct()
How to write (simple) LINQ to Entities query that groups elements by some attribut and count them?
SELECT answernumber, count(answerID) FROM answers
WHERE questionID = id
GROUB BY answernumber
ORDERBY answernumber;
That should be simple but i don't know how to write it.
var query = answers
.GroupBy(a => a.answernumber, a => a, (k, g) => new {answernumber = k, Count = g.Count()})
.OrderyBy(i => i.answernumber);
Or the other way:
var query2 = from a in answers
group a by a. answernumber into g
orderby g.Key
select new { answernumber = g.Key, Count = g.Count() };