LINQ to Entities: Convert SQL Sub Select - entity-framework

I got this figured out.
No need to answer.
The system says I have to wait 8 hours before answering my own questions. But for now the answer is below:
Here is the answer:
var startDate = DateTime.Today.AddDays(-30);
var results = (from h in Histories
join q in Quotes
on h.QuoteID equals q.QuoteID
join a in Agencies
on q.AgencyID equals a.AgencyID
where q.Status == "Inforce" &&
q.LOB == "Vacant" &&
q.EffectiveDate > startDate &&
h.Deleted == null &&
h.DeprecatedBy == null &&
h.TransactionStatus == "Committed" &&
a.DC_PLT_Roles.Any(r => r.Name == "Wholesaler")
group new {h} by new {h.PolicyNumber} into g
select new {
MaxHistoryID = g.Max (x => x.h.HistoryID),
comment = (from h2 in Histories
where h2.HistoryID == g.Max (x => x.h.HistoryID)
select h2.Comment).FirstOrDefault()
}).ToList();
The key code was:
comment = (from h2 in Histories
where h2.HistoryID == g.Max (x => x.h.HistoryID)
select h2.Comment).FirstOrDefault()
We are in the process of converting SQL / Stored Procedures to LINQ to Entities statements. And I can’t figure out the proper syntax for a sub select.
Currently I am converting this SQL:
declare #startDate DateTime
set #startDate = DATEADD(DD, -30, GETDATE())
select * from history where historyid in(
select MAX(h.historyid) as HistoryId
from History h (nolock)
inner join Quote q (nolock) on h.QuoteID = q.QuoteID
inner join Agency (nolock) a on q.AgencyID = a.AgencyID
inner join DC_PLT_EntityRoles er (nolock) on a.AgencyID = er.EntityID
inner join DC_PLT_Roles (nolock) r on er.RoleID = r.RoleID
where
q.Status = 'Inforce'
and q.LOB = 'Vacant'
and q.EffectiveDate > #startDate
and h.Deleted is null --
and h.DeprecatedBy is null --
and h.TransactionStatus = 'Committed'
and r.Name = 'Wholesaler'
group by h.PolicyNumber)
As you can see the code above is made up of two select statements. The main select (select * from history).. And a filter select (select MAX(h.historyid)…)
I got the filter select working (See below):
var startDate = DateTime.Today.AddDays(-30);
var results = (from h in Histories
join q in Quotes
on h.QuoteID equals q.QuoteID
join a in Agencies
on q.AgencyID equals a.AgencyID
where q.Status == "Inforce" &&
q.LOB == "Vacant" &&
q.EffectiveDate > startDate &&
h.Deleted == null &&
h.DeprecatedBy == null &&
h.TransactionStatus == "Committed" &&
a.DC_PLT_Roles.Any(r => r.Name == "Wholesaler")
group new {h} by new {h.PolicyNumber} into g
select new {
MaxHistoryID = g.Max (x => x.h.HistoryID)
}).ToList();
However I can’t figure out the proper syntax to set up the main select. (Basically getting the records from the History table using the HistoryID from the filter select.)
Any help would be appreciated.
Thanks for your help.

I figured it out, here is the code:
var startDate = DateTime.Today.AddDays(-30);
var results = (from h in Histories
.Include("Quote")
.Include("Quote.Agency")
where h.Quote.Status == "Inforce" &&
h.Quote.LOB == "Vacant" &&
h.Quote.EffectiveDate > startDate &&
h.Deleted == null &&
h.DeprecatedBy == null &&
h.TransactionStatus == "Committed" &&
h.Quote.Agency.DC_PLT_Roles.Any(r => r.Name == "Wholesaler")
group new {h} by new {h.PolicyNumber} into g
select new {
XMLData = (from h2 in Histories
where h2.HistoryID == g.Max (x => x.h.HistoryID)
select h2.XMLData).FirstOrDefault()
}).ToList();
The key logic is:
select new {
XMLData = (from h2 in Histories
where h2.HistoryID == g.Max (x => x.h.HistoryID)
select h2.XMLData).FirstOrDefault()
}).ToList();
Gotta love the Nested Query

Related

Linq Limit/Group by Id when joining IQueryables

I have a list of ids, that I then have multiple IQueryables that at the end I am joining to return my results. However some of these queries could have multiple records for that particular ID and I only need 1 record per ID from my set of x IDs. For example there could be 1 Name record, 3 Addresses, 2 Emails, 4 Phones for a single ID, but I only need 1 of each, does not matter which if multiple exist.
var clientNames = (
from n in db.Names
join cnl in db.ClientNameLinks on n.name_id equals cnl.name_id
where request.Ids.Contains(cnl.client_id)
&& n.name_id > 0
&& n.nametype_id != null
select new
{
n.display_name,
cnl.client_id
});
var clientAddresses = (
from a in db.Addresses
join cal in db.ClientAddressLinks on a.address_id equals cal.address_id
where request.Ids.Contains(cal.client_id)
&& a.address_id > 0
select new {
a.display_address,
cal.client_id
});
var clientEmails = (
from e in db.Emails
join cel in db.ClientEmailLinks on e.email_id equals cel.email_id
where request.Ids.Contains(cel.client_id)
&& e.email_id > 0
select new {
e.email_address,
cel.client_id
});
var clientPhones = (
from p in db.Phones
join cpl in db.ClientPhoneLinks on p.phone_id equals cpl.phone_id
where request.Ids.Contains(cpl.client_id)
&& p.phone_id > 0
select new {
p.phone_num,
cpl.client_id
});
var rows = await (
from n in clientNames
join a in clientAddresses on n.client_id equals a.client_id into n_a
from na in n_a.DefaultIfEmpty() //LEFT JOIN
join e in clientEmails on n.client_id equals e.client_id into n_e
from ne in n_e.DefaultIfEmpty() //LEFT JOIN
join ph in clientPhones on n.client_id equals ph.client_id into n_p
from np in n_p.DefaultIfEmpty() //LEFT JOIN
select new PiiDiamondClient
{
ClientId = n.client_id,
DisplayName = n.display_name,
DisplayAddress = na.display_address,
EmailAddress = ne.email_address,
PhoneExtension = np.phone_ext,
PhoneNumber = np.phone_num
}).Distinct().ToListAsync();
return rows.OrderBy(x => x.ClientId).ToList();
Your last query can be rewritten in the following way. It will exactly get one record from JOIN which can multiply result set.
var query =
from n in clientNames
from a in clientAddresses.Where(a => n.client_id == a.client_id)
.Take(1).DefaultIfEmpty() //OUTER APPLY or LEFT JOIN on ROW_NUMBER query
from e in clientEmails.Where(e => n.client_id == e.client_id)
.Take(1).DefaultIfEmpty() //OUTER APPLY or LEFT JOIN on ROW_NUMBER query
from ph in clientPhones.Where(ph => n.client_id == ph.client_id)
.Take(1).DefaultIfEmpty() //OUTER APPLY or LEFT JOIN on ROW_NUMBER query
select new PiiDiamondClient
{
ClientId = n.client_id,
DisplayName = n.display_name,
DisplayAddress = a.display_address,
EmailAddress = e.email_address,
PhoneExtension = ph.phone_ext,
PhoneNumber = ph.phone_num
};

How do you use aggregate functions in LINQ?

I can do this really easily in SQL but I can't translate it into LINQ.
The SQL:
SELECT EmployeeId
,YEAR(DistributionDate) AS DistributionYear
,SUM(SalesLocal * FX.ExchangeRate) AS TotalDistributions
FROM Distributions AS DD INNER JOIN FiscalPeriod AS FP ON DD.DistributionDate BETWEEN FP.StartDate AND FP.EndDate
INNER JOIN FXRates AS FX ON FP.FiscalPeriodId = FX.FiscalPeriodId AND FX.FromCurrencyId = DD.CurrencyId AND FX.ToCurrencyId = 'USD'
GROUP BY EmployeeId, YEAR(DistributionDate)
ORDER BY EmployeeId, DistributionYear
This is my broken attempt at translation:
var pointList = (from dd in db.Distributions
join e in db.Employee on dd.EmployeeId equals e.EmployeeId
join fp in db.FiscalPeriod.Where(p => dd.DistributionDate >= p.StartDate && dd.DistributionDate <= p.EndDate)
join fx in db.Fxrates on (fp.FiscalPeriodId equals fx.FiscalPeriodId) && (fx.FromCurrencyId equals dd.CurrencyId) && (fx.ToCurrencyId equals "USD")
group by dd.EmployeeId && dd.DistributionDate.Year
select new Point<int, decimal?>
{
X = dd.DistributionDate.Year,
Y = dd.Sum(dd.SalesLocal * fx.ExchangeRate)
}).ToList();
Visual Studio complains first that dd is not declared and then really complains once it reaches the join to Fxrates.
I think this may be close to what you want:
var pointList = (from dd in db.Distributions
join e in db.Employee on dd.EmployeeId equals e.EmployeeId
from fp in db.FiscalPeriod.Where(p => dd.DistributionDate >= p.StartDate && dd.DistributionDate <= p.EndDate)
from fx in db.Fxrates.Where(fx2 => fp.FiscalPeriodId == fx2.FiscalPeriodId && fx2.FromCurrencyId == dd.CurrencyId && fx2.ToCurrencyId == "USD")
group new { dd, fx } by new { dd.EmployeeId, dd.DistributionDate.Year } into distGroup
select new
{
X = distGroup.Key.Year,
Y = distGroup.Sum(d => d.dd.SalesLocal * d.fx.ExchangeRate)
}).ToList();

Select SQL case when for Entity Framework

I have this select which works in T-SQL, but need to convert to Entity Framework. How can I use case in Entity Framework?
select
*
from
Contrato c
where
c.QtdParcelasFalta > 0
and (case
when c.DiaEspecificoMarcar = 1
then c.DiaEspecifico
when c.DiaEspecificoMarcar = 0
then (select convert(int, substring(DataCobranca, 2, 2))
from Contrato
where Contrato.Id = c.Id) -
(select e.DataProcessamentoNota
from Contrato t
inner join PedidoVenda p on p.id = t.PedidoVendaId
inner join Empresas e on p.EmpresaID = e.Id
where p.id = t.PedidoVendaId
and t.id = c.Id and p.EmpresaID = 1)
end) = (SELECT DAY(GETDATE()))
I tried it like this, but it didn't work out, did not pass the correct values, because I'm not aware of pass to Entity Framework:
var contrato = db.Contrato
.Include(a => a.PedidoVenda)
.Include(a => a.Cliente)
.Where(a => a.PedidoVenda.EmpresaID == model.EmpresaID
&& a.Cancelado == false
&& a.DiaEspecificoMarcar == true
&& a.DiaEspecifico == int.Parse(DateTime.Now.ToString("dd")) ||
(int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota)
== int.Parse(DateTime.Now.ToString("dd"))
).ToList();
You are actually on the right track. You just need to add when conditions to your lef and right conditions like this:
var contrato = db.Contrato.Include(a => a.PedidoVenda).Include(a => a.Cliente).Where
(a => a.PedidoVenda.EmpresaID == model.EmpresaID && a.Cancelado == false &&
a.DiaEspecificoMarcar == false && a.DiaEspecifico == int.Parse(DateTime.Now.ToString("dd")) ||
( a.DiaEspecificoMarcar == true && int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota)
== int.Parse(DateTime.Now.ToString("dd"))
).ToList();
I also suggest you use DateTime.Now from a variable to be sure both int.Parse gets the same input

Trouble converting a SQL Query to the equivalent LinqToEntities code?

The short:
A simpler way of summing up this question would be, can you apply a conditon on a join in linq?
I have the following sql query:
select cdm.cashID, cdm.DateTimeTillOpened, cdm.DateTimeTillClosed, o.OrderID, o.OrderDate
from CashDrawsMonies cdm
join Orders o on o.OrderDate >= cdm.DateTimeTillOpened
AND o.OrderDate <= cdm.DateTimeTillClosed
join Users u on o.UserID = u.UserID
where u.UserID = 'C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A'
group by cdm.cashID, cdm.DateTimeTillOpened, cdm.DateTimeTillClosed, o.OrderID, o.OrderDate
order by o.OrderDate desc
Alternative SQL#
select *
from CashDrawsMonies cdm
where exists
(
select *
from Orders o
join Users u on o.UserID = u.UserID
where
o.OrderDate >= cdm.DateTimeTillOpened and
o.OrderDate <= cdm.DateTimeTillClosed and
u.UserID = 'C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A'
)
I can convert most queries but on the join in Linq it always asks for an equal keyword and not something like >= or <= which allows me in sql to put a condition on the join. This is what makes me scratch my head as to how do I convert it then?
My linq-To-Entites model in code (c#) is set-up as:
Cache.Model.Orders
Cache.Model.CashDrawMonies
Cache.Model.Users
Appreciate the help.
Attempt 1:
var results = from o in Cache.Model.Orders
from c in Cache.Model.CashDrawMoneys
join u in Cache.Model.Users on o.UserID equals u.UserID
where c.DateTimeTillOpened >= o.OrderDate
&& c.DateTimeTillClosed <= o.OrderDate
select c;
Attempt 2:
var results = from c in Cache.Model.CashDrawMoneys
from o in Cache.Model.Orders
where c.DateTimeTillOpened >= o.OrderDate
&& c.DateTimeTillClosed <= o.OrderDate
group c by new { c.cashID, c.DateTimeTillOpened, c.DateTimeTillClosed, o.OrderID, o.OrderDate, o.UserID } into temp
from t in temp
join u in Cache.Model.Users on t.UserID equals u.UserID
where t.UserID == selectedUser.UserID
select t;
Returns no results .... : S
UPDATE:
I re wrote my sql, the second peiece of sql does exactly what I want know. Just need someone to convert it for me somehow???
SQL Version 2 Converted Using Linqer:
from cdm in db.CashDrawMoneys
where
(from o in db.Orders
join u in db.Users on o.UserID equals u.UserID
where
o.OrderDate >= cdm.DateTimeTillOpened &&
o.OrderDate <= cdm.DateTimeTillClosed &&
u.UserID == new Guid("C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A")
select new {
o,
u
}).FirstOrDefault() != null
select new {
cdm.UserID,
cdm.DateTimeTillClosed,
cdm.DateTimeTillOpened,
cdm.LooseChange,
cdm.Fivers,
cdm.Tens,
cdm.Twenties,
cdm.Fifties,
cdm.IsOpen,
cdm.IsClosed,
cdm.ClosingValue,
cdm.OpeningValue,
cdm.cashID
}
Compiles nbut produces the following error:
"The argument to DbIsNullExpression must refer to a primitive or reference type."
The joins on the first Attempt look about right. But did you turn around the comparison operator?
where c.DateTimeTillOpened **>=** o.OrderDate
&& c.DateTimeTillClosed **<=** o.OrderDate
Update:
You can't create a new object within LINQ2EF as it doesn't know how to translate that to sql.
u.UserID == new Guid("C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A")
You'll have to define the GUID before the linq statement and then use the variable
var gid = new Guid("C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A")
from cdm in db.CashDrawMoneys
where
(from o in db.Orders
join u in db.Users on o.UserID equals u.UserID
where
o.OrderDate >= cdm.DateTimeTillOpened &&
o.OrderDate <= cdm.DateTimeTillClosed &&
u.UserID == gid
Below is what I managed to get:
var results = from cdm in Cache.Model.CashDrawMoneys
where (from o in Cache.Model.Orders
join u in Cache.Model.Users on o.UserID equals u.UserID
where o.OrderDate >= cdm.DateTimeTillOpened && o.OrderDate <= cdm.DateTimeTillClosed &&
u.UserID == selectedUser.UserID
select o).FirstOrDefault() != null
select cdm;
It's pretty close to what you got and did not have to worry about the guid as it was already created for me as I had a 'selectedUser' object.
The last line could be:
select o).Any()
select cdm;
But I'm not fussed, I get the two variations but Im gonna stick with my first version.

SQL "WHERE IN" query conversion to LINQ

I'm trying to find a way to convert this very complex SQL Query into LINQ and I can't seem to tackle all the embedded "WHERE IN" clauses. Would someone be so kind as to lend me a helping hand?
Here is the SQL code (don't worry about the stored procedure, it's a count of a row total)
SELECT
(SELECT pac.Name FROM Account pac WHERE pac.AccountID = AC.ParentAccountID) AS ParentAccountName,
ac.Name, dv.DeviceID, dv.Manufacturer, dv.Model, dv.SerialNr, dv.PrinterIPAddress,
(SELECT TOP 1 au.AuditDate FROM PrinterAudit pa WITH (NOLOCK) INNER JOIN Audit au ON au.AuditID = pa.AuditID
WHERE pa.DeviceID=dv.DeviceID
ORDER BY AuditDate DESC) AS AuditDate,
dbo.Get_TotalPageCountByDeviceId( DATEADD(month, -3, GETDATE()), GETDATE(), dv.DeviceID ) as TotalUsageLast3Months
FROM Account ac WITH (NOLOCK)
INNER JOIN Device dv ON ac.AccountID = dv.AccountID
WHERE dv.AccountID IN
( SELECT au.AccountID FROM Audit au WHERE au.AuditDate >= DATEADD(month, -3, GETDATE()) )
AND (dv.Manufacturer + dv.Model) IN
(SELECT (dv2.Manufacturer + dv2.Model)
FROM Device dv2
WHERE dv2.AccountID = dv.AccountID
AND dv2.Manufacturer = dv.Manufacturer
AND dv2.Model = dv.Model
AND (dv2.ERPEquipID IS NOT NULL OR dv2.ERPData IS NOT NULL ) )
AND dv.ERPEquipID IS NULL AND dv.ERPData IS NULL
AND dv.DeviceID IN
(SELECT pa.DeviceID
FROM PrinterAudit pa WITH (NOLOCK)
INNER JOIN Audit au ON au.AuditID = pa.AuditID
WHERE au.AuditDate >= DATEADD(month, -3, GETDATE()))
ORDER BY ParentAccountName, ac.Name
Final Result:
var result =
(from dv in Device
where Audit.Any(au => au.AuditDate >= DateTime.Now.AddMonths(-3)
&& au.AccountID == dv.AccountID)
where Device.Any(dv2 => dv2.AccountID == dv.AccountID
&& dv2.Manufacturer == dv.Manufacturer
&& dv2.Model == dv.Model
&& (dv2.ERPEquipID != null || dv2.ERPData != null)
&& dv.ERPEquipID == null
&& dv.ERPData == null
&& PrinterAudit.Any(pa => pa.Audit.AuditDate >= DateTime.Now.AddMonths(-3) && pa.DeviceID == dv.DeviceID))
orderby dv.Account.ParentAccountID, dv.Account.Name
select new
{
ParentAccountName = Account.Where(pac => pac.AccountID == dv.Account.ParentAccountID).Select(pac => pac.Name),
Name = dv.Account.Name,
DeviceID = dv.DeviceID,
Manufacturer = dv.Manufacturer,
Model = dv.Model,
SerialNumber = dv.SerialNr,
PrinterIPAddress = dv.PrinterIPAddress,
AuditDate = (from pa in PrinterAudit where pa.DeviceID == dv.DeviceID orderby pa.Audit.AuditDate descending select pa.Audit.AuditDate).Take(1),
TotalUsageLast3Months = (from p in PrinterAudit
where p.DeviceID == dv.DeviceID
group p by p.DeviceID into total
select new
{
Total = Get_TotalPageCountByDeviceId(DateTime.Now.AddMonths(-3), DateTime.Now, dv.DeviceID)
})
});
You convert the SQL IN statement to linq with either Contains or Any
Contains
from dv in db.Device
where
(from au in db.Audit
where au.AuditDate >= DateTime.Now.AddMonths(-3)
select au.AccountID).Contains(dv.AccountID)
Any
from dv in db.Device
where
db.Audit.Any(au => au.AuditDate >= DateTime.Now.AddMonths(-3) &&
au.AccountID == dv.AccountID)