I need help re-writing a SQL query into LINQ format - sql

I'm not good with LINQ yet and could use some help with the syntax.
Thanks!
The below query needs to be written in LINQ for C#.
SELECT Galleries.GalleryTitle, Media.*
FROM Galleries
INNER JOIN Media ON Galleries.GalleryID = Media.GalleryID
WHERE (Galleries.GalleryID = 150)
ORDER BY MediaDate DESC, MediaID DESC

Or with query syntax:
var query = from g in db.Galleries
join m in db.Media on g.GalleryID equals m.GalleryID
where g.GalleryID == 150
orderby m.MediaDate descending, m.MediaID descending
select new { g.GalleryTitle, Media = m };

Something like this:
var query = db.Galleries
.Join(db.Media, g => g.GalleryID, m => m.GalleryID, (g, m) => new {g, m})
.Where(r.g.GalleryID == 150)
.Select(res => new {res.g.GalleryTitle, Media = res.m}
.OrderByDescending(o => o.Media.MediaDate)
.ThenByDescending(o => o.Media.MediaID);

Related

I have a SQL query and I want to convert it to linq

I have a SQL query which I want to convert to Linq.
This is my SQL query:
SELECT
Calisanlar.CalisanId,
CovidYakalanmaTarih,
CovidBitisTarih
FROM
Calisanlar
INNER JOIN
Covids ON Calisanlar.CalisanId = Covids.CalisanId
WHERE
Calisanlar.CalisanId IN (SELECT TOP 10 CalisanId
FROM Hastaliklar
GROUP BY CalisanId
ORDER BY COUNT(*) DESC)
AND DATEDIFF(DAY, CovidYakalanmaTarih, GETDATE()) BETWEEN 0 AND 30
I wrote this C# code, but it doesn't work as expected because i didn't write "DATEDIFF(DAY, CovidYakalanmaTarih, GETDATE()) BETWEEN 0 AND 30" linq version:
var query = context.Hastaliklar
.GroupBy(x => x.CalisanId)
.OrderByDescending(grp => grp.Count())
.Select(grp => grp.Key)
.Take(10)
.ToList();
var result = from hastalik in context.Hastaliklar
join covid in context.Covids
on hastalik.CalisanId equals covid.CalisanId
where query.Contains(hastalik.CalisanId)
&& EF.Functions.DateDiffDay(covid.CovidYakalanmaTarih, covid.CovidBitisTarih)
select new SonBirAyCovidDto
{
CalisanId = covid.CalisanId,
CovidYakalanmaTarih = covid.CovidYakalanmaTarih,
CovidBitisTarih = covid.CovidBitisTarih
};
There is not direct translation to BETWEEN in EF Core, but you can make other condition. Also it is better to remove ToList() from first query, in this case you will have only one roundtrip to database.
var query = context.Hastaliklar
.GroupBy(x => x.CalisanId)
.OrderByDescending(grp => grp.Count())
.Select(grp => grp.Key)
.Take(10);
var result =
from hastalik in context.Hastaliklar
join covid in context.Covids
on hastalik.CalisanId equals covid.CalisanId
where query.Contains(hastalik.CalisanId)
&& covid.CovidYakalanmaTarih <= covid.CovidBitisTarih
&& EF.Functions.DateDiffDay(covid.CovidYakalanmaTarih, covid.CovidBitisTarih) <= 30
select new SonBirAyCovidDto
{
CalisanId = covid.CalisanId,
CovidYakalanmaTarih = covid.CovidYakalanmaTarih,
CovidBitisTarih = covid.CovidBitisTarih
};

Convert sql query to EF

Can anybody please help with this SQL query to transform it to EF Linq Expression?
select MI.Id, B.Count, B.Cost, Name, Price, Unity, I.Count, I.Cost, BOL.Date, BOL.type, BOL.Number
from Balance B inner join MaterialsInfo MI on Mi.Id = B.MaterialsId
inner join Income I on MI.Id = I.MaterialsId
inner join BillOfLading BOL on I.BillOfLadingId = BOL.Id
where B.Id in (select Id from (select max(Date), Id from Balance group by Balance.MaterialsId))
and I.Id in (select Id from(select max(Date), Income.Id as Id from Income inner join BillOfLading BOL on Income.BillOfLadingId = BOL.Id group by Income.MaterialsId))
I've been trying to do this for days, so I could really use some help.
Do you need extra info?
Thank you in advance.
Edit
Here is a little part of the diagram, maybe it helps
It seems the subqueries in both of your conditions in where clause is incorrect. Because your
group by column is missing in the select statement
And it is very unclear what you trying to achieve from the subqueries.
Without a clear understanding of your subqueries, all I can prepare for you is this.
var result = await (from balance in yourDBContect.Balances
join material in yourDBContect.MaterialsInfos on balance.MaterialsId equals material.Id
join income in yourDBContect.Incomes on material.Id equals income.MaterialsId
join bill in yourDBContect.BillOfLadings on income.BillOfLadingId equals bill.Id
where Balances.GroupBy(g => g.MaterialsId)
.Select(s => new
{
MaterialsId = s.Key,
MaxDate = s.Max(x => x.Date)
}).ToList().Contains(new { balance.MaterialsId, MaxDate = balance.Date })
&& Incomes.Join(BillOfLadings,
p => p.BillOfLadingId,
e => e.Id,
(p, e) => new { p, e })
.GroupBy(g => g.p.MaterialsId)
.Select(s => new
{
MaterialsId = s.Key,
MaxDate = s.Max(s => s.e.Date)
}).ToList().Contains(new { income.MaterialsId, MaxDate = balance.Date })
select new
{
material.Id,
balance.Count,
balance.Cost,
balance.Name,
balance.Price,
balance.Unity,
ICount = income.Count,
ICost = income.Cost,
bill.Date,
bill.Type,
bill.Number
});
Notes:
Alias for Income.Count and Income.Cost are changed because an object cannot contain exactly same nenter code hereamed property.
Linq for a proper subquery will replace new List<int>().

How can I write this query in linq?

I know there are probably a ton of questions like this already but i'm having trouble
select *
from [Group]
where GroupId not in
(select GroupId
from CustomerGroup
where CustomerId = 189621)
i have myGroups = db.Groups.Where(e=> e.GroupId), but how do i say not in?
i am kind of there
var myGroups = from a in db.Groups
where!(from b in db.CustomerGroups
where b.CustomerId == customer.CustomerId )
var groupIds = from cg in db.CustomerGroups
where cg.CustomerId == 189621
select cg.GroupId;
var myGroups = from g in db.Groups
where !groupIds.Contains(g.GroupId)
select g;
Need a list to disqualify first. NOT IN is basically a !(IEnumerable).Contains() in LINQ (since you're comparing to a set).
Using lambda expression, you probably can do it like this
var groupIds = db.CustomerGroups.Where(x => x.CustomerId == 189621).Select(x => x.GroupId);
var myGroups = db.CustomerGroups.Where(x => !groupIds.Contains(x.GroupId)).ToList();

SQL INNER JOIN with WHERE clause to LINQ format

How would I convert this sql query to LINQ?
SELECT company.ticker, company.primary_analyst,
personnel.last_name, company.research_associate,
company.secondary_associate, company.coverage_status
FROM company
INNER JOIN personnel ON company.primary_analyst = personnel.dpinitials
WHERE personnel.last_name='marley' AND company.associate='ml'
ORDER BY company.coverage_status
It's pretty similar:
var results = from c in company
join p in personnel on c.primary_analyst equals p.dpinitals
where p.last_name == 'marley' and c.associate == 'ml'
orderby c.coverage_status asc
select new
{
c.ticker, c.primary_analyst, p.last_name, c.research_associate,
c.secondary_associate, c.coverage_status
};
Above projects to an anonymous class with the properties you want - if you have an equivalent POCO class in your model you should project to that, if not in many cases you probably should create one.
The solution from #BrokenGlass is perfectly fine.
However, if you have a 1..many relationship it is rarely necessary to use the join operator in LINQ. In this example, if company->personell was 1..many, I would write the query like this:
var results = from c in company
where c.associate == "ml"
from p in c.personnel
where p.last_name == "marley"
orderby c.coverage_status asc
select new
{
c.ticker,
c.primary_analyst,
p.last_name,
c.research_associate,
c.secondary_associate,
c.coverage_status
};
This can also be written using the expression chain syntax:
var results = company.Where(c => c.associate == "ml")
.SelectMany(c => c.personnel, (c, p) => new
{
c.ticker,
c.primary_analyst,
p.last_name,
c.research_associate,
c.secondary_associate,
c.coverage_status
})
.Where(x => x.last_name == "marley")
.OrderBy(x => x.coverage_status)
var list = (from u in db.Users
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();

How do I translate this GROUP BY / MIN SQL query into LINQ?

I plan on using this in a subquery but can't figure out the correct syntax to translate the following query into LINQ:
select ChapterID, min(MeetingDate)
from ChapterMeeting
group by ChapterID
var query = myDataContext.ChapterMeeting
.GroupBy(cm => cm.ChapterID)
.Select(g => new {
g.Key,
MinMeetingDate = g.Min(cm => cm.MeetingDate)
});
Well, Amy beat me to it, but in case you wanted to see it with the "comprehension" syntax:
var q = (
from cm in context.ChapterMeeting
group cm by cm.ChapterID into cmg
select new {
ChapterID = cmg.Key,
FirstMeetingDate = cmg.Min(cm => cm.MeetingDate)});