LINQ Query multiple orderby of joined tables - c#

I have following LinQ query
var CGTABLE = (from cg in DbContext.CGTABLE
join tcg in DbContext.TCGTABLE on new { cg.CGroupId } equals new { tcg.CGroupId }
where tcg.TId == TId
select new {
CGroupId = cg.CGroupId,
CGroupCode = cg.CGroupCode,
Description = cg.Description,
C = cg.C,
DisplayOrder = cg.DisplayOrder
}).ToList();
CGTABLE = CGTABLE.OrderBy(g => g.DisplayOrder).ThenBy(g => g.C.OrderBy(c => c.CCode)).ToList();
which runs fine, but it is not doing second orderby using ThenBy ThenBy(g => g.C.OrderBy(c => c.CCode) What am I missing?
Sample data for better understanding.
Data in Tables
2
1
2
4
3
1
4
5
2
1
3
3
1
Should output after both outer and inner list ordered by
1
1
2
3
4
2
1
2
4
5
3
1
3
But Currently it is showing
1
4
5
2
1
2
1
2
4
3
3
3
1

You didn't want to order the main list, you are looking for a way to order inner list inside of outer one, I think.
So below code will do it for you:
var CGTABLE = (
from cg in DbContext.CGTABLE
join tcg in DbContext.TCGTABLE on new { cg.CGroupId } equals new { tcg.CGroupId }
where tcg.TId == TId
select new {
CGroupId = cg.CGroupId,
CGroupCode = cg.CGroupCode,
Description = cg.Description,
C = cg.C.OrderBy(x => x.CCode),
DisplayOrder = cg.DisplayOrder
}).ToList();
CGTABLE = CGTABLE.OrderBy(g => g.DisplayOrder).ToList();

Related

Join with last record of details table

Please consider these two tables in my database:
Header:
Id Name
-------------------------------
1 London
2 Berlin
3 Paris
and Details:
Id HeaderId Amount YearMonth
--------------------------------------------------------------------
1 1 1000 2010-01
2 1 2000 2010-05
3 2 3000 2015-04
4 2 2700 2017-12
5 2 4500 2016-10
6 2 7000 2011-09
7 1 3000 2009-05
I want Header records with related Last Details record. For example:
HeaderId HeaderName Amount
----------------------------------------------------
1 London 2000
2 Berlin 2700
3 Paris Null
I wrote this query for Inner Join version (But I want Outer Join version):
from h in Header
join d in Details
on h.Id equals d.HeaderId
select new
{
HeaderId = h.Id,
HeaderName = h.Name,
Amount = (Details.Where(k=>k.HeaderId == h.Id).OrderBy(m=>m.YearMonth).LastOrDefault() == null ? null : Details.Where(k=>k.HeaderId == h.Id).OrderBy(m=>m.YearMonth).LastOrDefault().Amount,
}
and I got this error:
System.NotSupportedException: LINQ to Entities does not recognize the method 'Details.LastOrDefault()Details' method, and this method cannot be translated into a store expression.
How can I get above result?
thanks
This query should return desired result:
from h in Header
from d in Details.Where(d => d.HeaderId == h.Id)
.OrderByDescending(d => d.YearMonth)
.Take(1)
.DefaultIfEmpty()
select new
{
HeaderId = h.Id,
HeaderName = h.Name,
Amount = d.Amount
}
You should change your code as :
Amount = Details.Where(k=>k.HeaderId == h.Id).OrderByDescending(m => m.YearMonth).FirstOrDefault(o=>o.Amount);

Convert SQL to LINQ Troubles

I have been stuck on this for an embarrassing day... can't seem to convert this to linq. My issue also is that Attendee can be null.
select c.activityId, count(distinct b.attendeeId)
from Attendee a, sponsor_activity c
left outer join sponsor_attendance b
on c.ActivityId = b.ActivityId
where a.RegistrationId = 62
AND c.SponsorLevelId = 2
group by c.activityId
So far I have this code... but I am not getting distinct values
var activity_count = (from c in db.Sponsor_Activitys
where c.SponsorLevelId == pledgelvl
from a in db.Attendees.DefaultIfEmpty()
where a.RegistrationId == registration
select new { Activityid = c.ActivityId, NumAttending = db.Sponsor_Attendances.Count(x => x.ActivityId == c.ActivityId) })
.ToList();
Sponsor_Attendance
AttendanceId
AttendeeId
ActivityId
Sponsor_Activity
ActivityId
SponsorLevelId
Attendee
AttendeeId
RegistrationId
Returns:
## ActivityID ## ## NumAttending ##
2 4
3 0
4 2
2 4
3 0
4 2
2 4
3 0
4 2
Currently there are 3 attendees that have a registrationid that matches... so this is why it is repeated 3 times in the output.
First, it helps if your original queries are readable. :)
Query:
SELECT c.activityId
, COUNT(DISTINCT b.attendeeId)
FROM Attendee a
, sponsor_activity c
LEFT OUTER JOIN sponsor_attendance b
ON c.ActivityId = b.ActivityId
WHERE a.RegistrationId = 62 AND
c.SponsorLevelId = 2
GROUP BY c.activityId;
Linq:
var activity_count = (from activity in db.Sponsor_Activitys
where activity.SponsorLevelId == pledgelvl
from attendee in db.Attendees.DefaultIfEmpty()
where attendee.RegistrationId == registration
select new
{
Activityid = activity.ActivityId,
NumAttending = db.Sponsor_Attendances.Count(x => x.ActivityId == activity.ActivityId)
}).ToList();
My answer:
var query = from activity in db.Sponsor_Activitys
// Left outer join onto sponsor_attendances
join attendance in db.Sponsor_Attendances
on activity.ActivityId equals attendance.ActivityId into g
from q in g.DefaultIfEmpty()
join attendee in db.Attendees
on q.AttendeeId equals attendee.AttendeeId
where attendee.RegistrationId == registration &&
activity.SponsorLevelId == pledgelvl
select new
{
Activityid = activity.ActivityId,
NumAttending = db.Sponsor_Attendances.Count(x => x.ActivityId == activity.ActivityId)
}
Given the cartesian join (typically bad!), this might be a better example on just executing SQL rather than trying to convert to Linq.

Recursive get all childrens using LINQ C#

i want to show all the parentID as possible using linq for example:
if i select "submodule_idparent = 6" return all 5 and return 1. Because, to show 6 i need 5 and 1.
submodule_id, submodule_name, submodule_idparent
1 Articles null
2 Suppliers null
3 Adjustment 1
4 Presentations 1
5 Categories 1
6 Subcategories 5
7 Corridors 1
8 Cellars 1
9 Purchases 2
I'm try some like that with the next code (MySQL)
SELECT DISTINCT(submodule_id) FROM users_privileges LEFT JOIN modules_options USING(moduleoption_id) WHERE users_privileges.user_id = 1
but is not recursive.
Thanks in advance (y).
Try this:
var query=GetAll(6);
public IEnumerable<users_privileges> GetAll(int submodule_id)
{
var query = from c in db.users_privileges
where c.submodule_id == submodule_id
select c;
return query.ToList().Concat(query.ToList().SelectMany(t => GetAll(t.submodule_idparent)));
}
http://blog.csdn.net/q107770540/article/details/7708418

convert an sql query into linq to entities method based

i have got this query in sql server server that do what i want..
how can i convert it to linq
select t1.IDHardware,h.DescricaoHardware
from dbo.ProcessoHardware t1
INNER JOIN
(select t2.IDHardware, max(t2.IDProcessoHardware) as maxVisit
from dbo.ProcessoHardware t2
group by t2.IDHardware,t2.IDProcesso) v ON
v.maxVisit = t1.IDProcessoHardware JOIN dbo.Hardware h ON t1.IDHardware=h.IDHardware
where t1.Estado=1 AND IDProcesso=1
this is where i am now...but i am unable to figure it past this point..
var ProcHardware = (from procHardware in db.ProcessoHardwares
where procHardware.IDProcesso == IDProcesso
select new { procHardware.IDHardware, procHardware.IDProcessoHardware, procHardware.IDProcesso, procHardware.Estado } into x
group x by new { x.IDHardware, x.IDProcesso, x.IDProcessoHardware, x.Estado } into t
let Max = t.Max(g => g.IDProcessoHardware)
select new { IDHardware = t.Key.IDHardware, Estado = t.Key.Estado, t.Key.IDProcesso,IDProcessoHardware=t.Key.IDProcessoHardware,cMax=Max }).ToList().Where(t => t.Estado == 1 && t.IDProcesso == IDProcesso && t.IDProcessoHardware==Max).Select(c => new VMProcessoChooseHardware
{
IDHardware = c.IDHardware
});
i have got this table that relates the Table hardware with a table Process.. this table is called processHardware. this table is discribed by: IDProcessHardware IDProcess IDHardware State
the field state can have 3 states (1-Insert, 2-Remove,3-Substitute).. so i can i have this:
IDProcessHardware IDProcess IDHardware State
1 10 1 1
2 10 2 1
3 10 1 2
4 10 1 1
5 20 1 1
what i want to get is get the IDHardware that were inserted but not removed from process.
so by giving the IDProcess = 10 i want to get the hardware with the hardware ids 1 and 2..
IDProcessHardware IDProcess IDHardware State
1 10 1 1
2 10 2 1
3 10 1 2
4 20 1 1
in the table above by giving the IDProcess 10 , it should give me the Hardware ids 2.
Thanks in advance...
After a lot of trial and error, and a lot of search i found this link
http://jetmathew.wordpress.com/2014/01/21/select-latest-record-from-recordset-using-sql-and-linq/
the guy was trying something similar to what i want..
so i pick the linq query and transform it..
this is what i have now
var ProcHardware = (from a in db.ProcessoHardwares
group a by new { a.IDHardware, a.IDProcesso } into latest
join b in db.ProcessoHardwares on new { dt = latest.Max(itm => itm.IDProcessoHardware) } equals new { dt = b.IDProcessoHardware }
select new { ID = b.IDHardware, Estado=b.Estado,IDProcesso=b.IDProcesso }).ToList().Where(t => t.Estado == 1 && t.IDProcesso == IDProcesso ).Select(c => new VMProcessoChooseHardware
{
IDHardware = c.ID
});
it still need the rest the information discribing the hardware like the serial number , or the description.
i will post here the complete query..

How to select from 3 tables in a series using Linq?

I have 3 tables:
Degree(Id int(PK), DegreeName string)
1 Bachelor
2 Master
3 PhD
Track(Id int(PK), DegreeId int(FK), TrackName string)
1 2 Engineer
2 1 Technician
3 1 Assistant
4 2 Physicist
5 3 Doctor
Group(Id int(PK), TrackId int(FK), GroupName string)
1 4 Group1
2 3 Group2
3 1 Group3
4 3 Group4
5 2 Group5
there is a one to many relation between Degree and Track, and another one to many relation between Track and Group.
I have this class:
Public class DegreeDetails
{
public List<Track> TrackList { get; set; }
public List<Group> GroupsList { get; set; }
}
to get all tracks these belong to bachelor degree, which are technician and assistant, I use this code:
In the controller I use this code:
DegreeDetails MyView = new DegreeDetails();
MyView.TrackList = entity.Track.Where(s => s.DegreeID == 1).ToList();
how to get a Group List of all groups these study tracks belong to bachelor degree, which should be Group2, Group4 and Group5.
Probably the best thing to do is to join these tables. You could create a view in your database, or you can join tables using Linq.
This should work:
MyView.GroupList = (from d in entity.Degree
join t in entity.Track on d.Id equals t.DegreeId
join g in entity.Group on t.Id equals g.TrackId
where d.Id == 1
select g).Distinct().ToList();
UPDATE If you want to use lambda exp, try this:
MyView.GroupList = entity.Degree.Where(d => d.Id == 1)
.Join(entity.Track, d => d.Id, t=> t.DegreeId, (d, t) => t)
.Join(entity.Group, t => t.Id, g => g.TrackId, (t, g) => g)
.Distinct().ToList();
You should join tracks with groups:
var groupList = entity.Track.Where(s=>s.DegreeID == 1).Join(entity.Group, t=>t.Id, g=>g.TrackId, (t,g)=>g).ToArray();

Categories

Resources