Linq query with a Conditional WHERE Clause - c#

I am new to LINQ so apologises upfront
I have the following Linq query :-
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys
on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a =>
a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
I need to include a where clause in the above query ... only if a variable called
BranchKeySelected is ""
I have tried using an If Else statement and have the same above query duplicated with
one containing a where clause and one NOT. ...But When I do this .. then OrdersByBranches
is NOT available outside of the IF Statement
Would be grateful for any help
Regards
Ghost

var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new {
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
if(string.IsNullOrEmpty(BranchKeySelected ))
{
OrdersByBranches = OrdersByBranches.Where(/*blbabla*/);
}
return OrdersByBranches;

Try (and my linq is not polished)
var OrdersByBranches = from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
where b.BranchKeySelected.Contains("")
orderby a.Date group a by new
{
a.Date,
a.paymentMethod
}
into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};

Related

Sql Join Subquery output in Linq

I'm write some SQL query with join and sub query i want convert into linq
select a.CampaignId, a.ImagePath,(select Count(a1.CampaignId) from INN_Customers_Campaigns_Images a1 where a1.CampaignId = a.CampaignId)ImageCount from INN_Customers_Campaigns_Images a
inner join INN_Customers_Gallary b On b.CampaignId = a.CampaignId and a.CreatedBy = b.CustomerId
You can use let clause for your sub query
var result = from a in context.INN_Customers_Campaigns_Images
join b in context.INN_Customers_Gallary on new { a.CampaignId , a.CreatedBy } equals new { b.CampaignId , b.CustomerId }
let imageCount = context.INN_Customers_Campaigns_Images.Where(a1 => a1.CampaignId == a.CampaignId).Count()
select new
{
a.CampaignId,
a.ImagePath
ImageCount = imageCount
}

Left join and case clause LINQ in Entity Framework

I am needing to make a left join and also use the select operator case.
My LINQ basic is this and works:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao
});
But I must add a new field and it should be formatted, then my LINQ looked like this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")
}
);
This error happens:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
If you add the ToList() or AsEnumerable() in db.AgendaHorario.ToList() and db.Agenda.ToList() and db.Profissional.ToList() error that appears is:
Object reference not set to an instance of an object.
What should I do to have a left join with case and fields and formatted fields
Try this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario
}).AsEnumerable().Select(x => new
{
id = x.id,
Medico = x.Medico,
start = x.start.ToString("yyyy-MM-dd HH:mm:ss")
}
);
try to set the string in a variable then assign it to your query like this:
var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");
resultado.Dados = (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = myValue
} );

Sql Query to Linq using IN

I have a Sql Query like :
select distinct FROM_EMAILID,FROM_COUNTRY from SURVEY_VISITORS
where FROM_COUNTRY IN
(
select top 1 FROM_COUNTRY as FROM_COUNTRY from SURVEY_VISITORS
where FROM_COUNTRY<>'undefined'
group by FROM_COUNTRY order by COUNT(*) desc
)
I'm unable to handle with IN Operator.
Any help would be greatly appreciated.
For the sub-Query,I've tried this way :
var innerQuery = (from t in VDC.SURVEY_VISITORS
group t by new
{
t.FROM_COUNTRY
} into g
orderby
g.Count() descending
select new
{
VisitorCount = (Int64?)g.Count(),
Country = g.Key.FROM_COUNTRY
}).FirstOrDefault();
var innerQuery = (from t in VDC.SURVEY_VISITORS
group t by new
{
t.FROM_COUNTRY
} into g
orderby
g.Count() descending
select new
{
VisitorCount = (Int64?)g.Count(),
Country = g.Key.FROM_COUNTRY
}).FirstOrDefault();
var result = (from xx in VDC.SURVEY_VISITORS
where ((innerQuery.Country.Contains(xx.FROM_COUNTRY)) && xx.TEMPLATE_ID == RecentBlastedTemplate.TEMPLATE_ID)
select new
{
xx.FROM_COUNTRY,
xx.FROM_EMAILID
}).Distinct().ToList();

Joining two tables in linq method syntax, MVC EntityFramework

I'm working with two tables: CI_CLIENTRISK (SCD type 2)... and QB_INVOICES_HEADER (edmx screenshot).
They can be joined via ClientID. I want to essentially replicate this query:
SELECT a.ClientID,
MAX(b.InvoiceDt) AS MaxInvoiceDt
(omitted for brevity)
FROM CI_CLIENTRISKADJS a
INNER JOIN QB_INVOICES_HEADER b
ON a.ClientID = b.ClientID
WHERE a.IsActive = 1
GROUP BY a.ClientID
ORDER BY MaxInvoiceDt DESC
Here's what I have so far. It's not returning any records.
using (var db = new PLOGITENS01Entities())
{
var rvClientRiskAdjs = db.CI_CLIENTRISKADJS
.Take(50)
.Join(db.QB_INVOICES_HEADER,
a => a.ClientID,
b => b.ClientID,
(a, b) => new { Risk = a, Invoices = b })
.Where(a => a.Risk.IsActive == 1)
.OrderByDescending(o => o.Invoices.InvoiceDt)
.Select(c => new ClientRiskModel()
{
ClientRiskId = c.Risk.ClientRiskID,
ClientName = c.Risk.CI_CLIENTLIST.ClientName,
ClientId = c.Risk.ClientID,
ClientRiskAdjs = c.Risk.ClientRiskAdjs,
RecordValidStartDt = c.Risk.RecordValidStartDt,
RecordValidEnddt = c.Risk.RecordValidEnddt,
IsActive = c.Risk.IsActive
})
.ToList();
return View(new GridModel(rvClientRiskAdjs));
}
Try putting your .Take(50) method after your final .Select and before .ToList(). As it is, you are only taking the first 50 records of the first table and then joining from there. I'm assuming that there are no joins to the second table in the first 50 records of the first table; therefore, your result will have 0 records.
I stumbled across this solution from reading this post: https://stackoverflow.com/a/157919/1689144
var rvClientRiskAdjs = (from ri in db.CI_CLIENTRISKADJS
join qb in
(from qb in db.QB_INVOICES_HEADER
orderby qb.InvoiceDt ascending
group qb by qb.ClientID into grp
select new
{
InvoiceDt = grp.Max(s => s.InvoiceDt),
ClientID = grp.Key
})
on ri.ClientID equals qb.ClientID
orderby qb.InvoiceDt descending
where ri.IsActive == 1
select new ClientRiskModel()
{
ClientRiskId = ri.ClientRiskID,
ClientName = ri.CI_CLIENTLIST.ClientName,
ClientId = ri.ClientID,
ClientRiskAdjs = ri.ClientRiskAdjs,
RecordValidEnddt = ri.RecordValidEnddt,
RecordValidStartDt = ri.RecordValidStartDt
})
.ToList();

Select a field that is not in Group By clause in LINQ

could anybody help me about
"How to select a field that is not in Group By clause in LINQ"
var ReportData =
from a in context.Table1
from b in context.Table2
where a.personelID == b.ID
&& a.DateField.Value.Year == 2011
group a by new { a.personelID, b.Name, b.Surname} into grouping
select new
{
// grouping.Key.DateField,
Name= grouping.Key.Name,
Surname= grouping.Key.Surname,
PagaBruto = grouping.Sum(i => i.Bruto)),
};
I can't select the field "DateField" that is in Table1, I don't want to have this field in Group By, because I will get a wrong result.
THANKS!
I think you need to select both table members before you group by so you can select data from both. I did a join instead of your where clause.
(from a in context.Table1
join b in context.Table2 on a.PersonalID equals b.ID
select new { A=a, B=b } into joined
group joined by new { joined.A.PersonalID, joined.B.Name, joined.B.Surname } into grouped
select grouped.Select(g => new {
DateField= g.A.Datefield,
Name = g.B.Name,
Surname = g.B.Surname,
PagaBruto = g.A.Sum(i => i.Bruto)
})).SelectMany(g => g);
Maybe this will work?
group a by new { a.personelID, b.Name, b.Surname, a.DateField} into grouping
select new
{
DateField = grouping.Key.DateField,
Name= grouping.Key.Name,
Surname= grouping.Key.Surname,
PagaBruto = grouping.Sum(i => i.Bruto)),
};

Categories

Resources