C# Linq compress join query with where clause - c#

Hi I am using below code to fetch required data from 2 tables using linq syntax which is working fine.
var ratings = from r in _ratingRepository.AsQueryable()
join c in _convRepository.AsQueryable()
on r.SessionId equals c.CurrentConversationSid
where!c.IsDeleted && c.DateCreated >= request.From && c.DateCreated <=
request.To && c.HasRated
select new Rating() {
Id = r.Id,
SessionId = r.SessionId,
Questions = r.Questions,
AvgRatingValue = r.AvgRatingValue
};
I want to transform this code using below syntax
IQueryable<Rating> ratingsObj = _ratingRepository.AsQueryable()
.Join(_convRepository.AsQueryable().Where(a => a.HasRated), r => r.SessionId, c => c.CurrentConversationSid, (r, c) =>
new Rating()
{
Id = r.Id,
SessionId = r.SessionId,
Questions = r.Questions,
AvgRatingValue = r.AvgRatingValue
});
Its gives below error
System.ArgumentException: 'Expression of type
'System.Collections.Generic.IEnumerable1[Flecx.Chat.Entities.Conversation]' cannot be used for parameter of type 'System.Linq.IQueryable1[Flecx.Chat.Entities.Conversation]' of method
'System.Linq.IQueryable1[Flecx.Chat.Entities.Conversation] Where[Conversation](System.Linq.IQueryable1[Flecx.Chat.Entities.Conversation],
System.Linq.Expressions.Expression1[System.Func2[Flecx.Chat.Entities.Conversation,System.Boolean]])'
(Parameter 'arg0')'
If I remove this code .Where(a => a.HasRated) it runs fine. How can I include the where clause in above syntax.
Need help

try this:
var ratingsObj = _ratingRepository.AsQueryable()
.Join(_convRepository.AsQueryable(),
r => r.SessionId,
c => c.CurrentConversationSid,
(r,c)=>new {r,c}) //**
.Where(a => a.c.HasRated)
.Select(x => new Rating()
{
Id = x.r.Id,
SessionId = x.r.SessionId,
Questions = x.r.Questions,
AvgRatingValue = x.r.AvgRatingValue
});
you can filter anything you want in line with '//**' same below:
(r, c) => new
{ r.Id,
r.SessionId,
r.Questions,
r.AvgRatingValue,
c.HasRated
}
then your code is changed to this:
var ratingsObj = _ratingRepository.AsQueryable()
.Join(_convRepository.AsQueryable(),
r => r.SessionId,
c => c.CurrentConversationSid,
(r, c) => new
{ r.Id,
r.SessionId,
r.Questions,
r.AvgRatingValue,
c.HasRated})
.Where(a => a.HasRated)
.Select(x => new Rating()
{
Id = x.Id,
SessionId = x.SessionId,
Questions = x.Questions,
AvgRatingValue = x.AvgRatingValue
});

Related

Linq-to-SQL query (AsEnumerable) on multiple tables

Here's a Linq-to-SQL query that uses only one table from my SQL Server database and works perfectly:
private void GetData()
{
DateTime d = DateTime.Now;
using (DataClasses1DataContext dc = new DataClasses1DataContext())
{
var qte = dc.ENTREES_STOCKS.AsEnumerable()
.Where(x => x.ENTSTK_LOT == lot)
.Where(x => x.ART_CODE == artCode)
.Where(x => x.ENTSTK_USER == null)
.Select(s => new
{
art = s.ART_CODE,
date = s.ENTSTK_DTENTREE,
numLot = s.ENTSTK_LOT,
pnet = s.ENTSTK_PNET,
nbu = s.ENTSTK_NBU
})
.GroupBy(g => new { g.art, g.date, g.numLot })
.Select(n => new
{
n.Key.art,
n.Key.date,
n.Key.numLot,
pnet = n.Sum(x => Math.Round(Convert.ToDecimal(x.pnet), 2)),
nbu = n.Sum(x => Math.Round(Convert.ToDecimal(x.nbu), 2)),
});
QEntreeTB.Text = qte.First().pnet.ToString();
NbuEntreeTB.Text = qte.First().nbu.ToString();
}
}
How could I modify this code to join other tables to this query like :
private void GetData()
{
DateTime d = DateTime.Now;
using (DataClasses1DataContext dc = new DataClasses1DataContext())
{
var qte = dc.ENTREES_STOCKS.AsEnumerable()
// Thoseline of codes of course doesn't work
join art in dc.FICHES_ARTICLES on ENTREES_STOCKS.ART_CODE equals art.ART_CODE
join ent in dc.STK_ENT on art.ART_CODE equals ent.ART_CODE
....
//
.Where(x => x.ENTSTK_LOT == lot)
.Where(x => x.ART_CODE == artCode)
.Where(x => x.ENTSTK_USER == null)
.Select(s =>
new
{
art = s.ART_CODE,
date = s.ENTSTK_DTENTREE,
numLot = s.ENTSTK_LOT,
pnet = s.ENTSTK_PNET,
nbu = s.ENTSTK_NBU
}
)
.GroupBy(g => new { g.art, g.date, g.numLot })
.Select(n =>
new
{
n.Key.art,
n.Key.date,
n.Key.numLot,
pnet = n.Sum(x => Math.Round(Convert.ToDecimal(x.pnet), 2)),
nbu = n.Sum(x => Math.Round(Convert.ToDecimal(x.nbu), 2)),
}
);
QEntreeTB.Text = qte.First().pnet.ToString();
NbuEntreeTB.Text = qte.First().nbu.ToString();
}
}
Or is there à way to code this query another way ??
Because in fact i just want to join multiples tables, groupby some fields and sum others fields.
Firstly, calling AsEnumerable is a bit redundent. Then you can simply use the Join extension method.
var qte = dc.ENTREES_STOCKS
.JOIN(dc.FICHES_ARTICLES,art=>art.ART_CODE, stock => stock.ART_CODE)
.JOIN(dc.STK_ENT,ent => ent.ART_CODE,stock => stock.ART_CODE)
.Where(x => x.ENTSTK_LOT == lot)
.Where(x => x.ART_CODE == artCode)
.Where(x => x.ENTSTK_USER == null)
....
You can find more answers here:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/method-based-query-syntax-examples-join-operators

Translating SQL to lambda with groupby

I'm trying to translate this sql statement
SELECT row, SUM(value) as VarSum, AVG(value) as VarAve, COUNT(value) as TotalCount
FROM MDNumeric
WHERE collectionid = 6 and varname in ('C3INEV1', 'C3INEVA2', 'C3INEVA3', 'C3INVA11', 'C3INVA17', 'C3INVA19')
GROUP BY row
into an EF 4 query using lambda expressions and am missing something.
I have:
sumvars = sv.staticvararraylist.Split(',');
var aavresult = _myIFR.MDNumerics
.Where(r => r.collectionid == _collid)
.Where(r => sumvars.Contains(r.varname))
.GroupBy(r1 =>r1.row)
.Select(rg =>
new
{
Row = rg.Key,
VarSum = rg.Sum(p => p.value),
VarAve = rg.Average(p => p.value),
TotalCount = rg.Count()
});
where the staticvararraylist has the string 'C3INEV1', 'C3INEVA2', 'C3INEVA3', 'C3INVA11', 'C3INVA17', 'C3INVA19' (without single quotes) and the _collid variable = 6.
While I'm getting the correct grouping, my sum, average, & count values aren't correct.
You didn't post your error message, but I suspect it's related to Contains. I've found that Any works just as well.
This should get you quite close:
var result =
from i in _myIFR.MDNumerics
where i.collectionid == _collid && sumvars.Any(v => i.varname == v)
group i by i.row into g
select new {
row = g.Key,
VarSum = g.Sum(p => p.value),
VarAve = g.Average(p => p.value),
TotalCount = g.Count()
};
Try this:
var aavresult = _myIFR.MDNumerics
.Where(r => r.collectionid == _collid && sumvars.Contains(r.varname))
.GroupBy(r1 =>r1.row,
(key,res) => new
{
Row = key,
VarSum = res.Sum(r1 => r1.value),
VarAve = res.Average(r1 => r1.value),
TotalCount = res.Count()
});

Multiple Select and Join with LINQ and Lambda

How can I do this query using LINQ and LAMBDA ?
QUERY
Select san_negocio.imovel_id
,san_negocio.negocio_id
,san_imovel.credenciada_id
,san_proposta.proposta_id
,san_proposta.credenciada_id
from san_negocio
join san_proposta
on san_negocio.imovel_id = san_proposta.imovel_id
join san_imovel
on san_negocio.imovel_id = san_imovel.imovel_id
where san_negocio.credenciadacaptadora_id is null
and san_negocio.credenciadavendedora_id is null
and san_proposta.statusproposta_id = 2
I've tried:
var objetos = db.San_Negocio.Join(db.San_Proposta, a => a.Imovel_Id, b => b.Imovel_Id, (a, b) => new { San_Negocio = a, San_Proposta = b })
.Join(db.San_Imovel, a => a.San_Negocio.Imovel_Id, c => c.Imovel_Id, (a, c) => new { San_Negocio = a, San_Imovel = c })
.Where(a => a.San_Negocio.San_Negocio.CredenciadaCaptadora_Id == null && a.San_Negocio.San_Negocio.CredenciadaVendedora_Id == null)
.Select(a => new { a.San_Negocio.San_Negocio.Negocio_Id,
a.San_Negocio.San_Negocio.Imovel_Id,
a.San_Imovel.Credenciada_Id });
My doubt is in my Select. How can I call my San_Proposta table ?
You are hiding San_Proposta within a field called San_Negocio, so calling a.San_Negocio.San_Proposta will access it, but I recommend writing your joins in a way that fields aren't nested, like this:
var objetos = db.San_Negocio
.Join(db.San_Proposta,
a => a.Imovel_Id,
b => b.Imovel_Id,
(a, b) => new { San_Negocio = a, San_Proposta = b })
.Join(db.San_Imovel,
a => a.San_Negocio.Imovel_Id,
c => c.Imovel_Id,
(a, c) => new { a.San_Negocio, a.San_Proposta, San_Imovel = c })
.Where(a => a.San_Negocio.CredenciadaCaptadora_Id == null &&
a.San_Negocio.CredenciadaVendedora_Id == null)
.Select(a => new
{
a.San_Negocio.Negocio_Id,
a.San_Negocio.Imovel_Id,
a.San_Proposta.San_Proposta_Id,
a.San_Imovel.Credenciada_Id
});
Here is a proper linq statement:
from neg in db.san_negocio
join prop in san_proposta
on neg.imovel.id equals prop.imovel_id
join imo in san_imovel
on neg.imovel_id = imo.imovel_id
where neg.credenciadacaptadora_id == null &&
neg.credenciadavendedora_id == null &&
prop.statusproposta_id == 2
select new {
ImovelID = neg.imovel_id,
NegocioID = neg.negocio_id,
Imo_CredenciadaID = imo.credenciada_id,
PropostaID = prop.proposta_id
Prop_CredenciadaID = prop.credenciada_id
};
This will create an IQueryable of anonymous objects with the listed properties above.

How to use LINQ with calculated properties in a single pass?

I'd like to make a LINQ query, extracting dynamic properties (calculated fields) of my entities in a single pass, without get the error "The specified type member 'EntityKey' is not supported in LINQ to Entities".
Here is the only working way I found, but I am sure there are better and more elegant methods:
var q = (from i in
(from x in context.Tickets
select new { x.OperatoreID, x.DataObiettivo })
group i by new { i.OperatoreID } into g
select new vmOperatoreDateObiettivo
{
OperatoreID = g.Key.OperatoreID,
NOperatore = "", // field value to be updated...
DataObiettivo = g.Max(d => d.DataObiettivo),
MinutiAllaScadenza = 0, // field to be updated...
Alert = "" // field value to be updated...
}).ToList();
// Here I update my fields with a second pass....
foreach (vmOperatoreDateObiettivo e in q)
{
string nome = context.Operatori
.Where(t => t.OperatoreID == e.OperatoreID)
.First().CognomeNomePuntato.ToString();
e.NOperatore = nome;
int minscad = context.Tickets
.Where(t => t.OperatoreID == e.OperatoreID).AsEnumerable().Min(a => a.MinutiAllaScadenza);
e.MinutiAllaScadenza = minscad;
string sev = context.Tickets
.Where(t => t.OperatoreID == e.OperatoreID).AsEnumerable().Min(a => a.Alert);
e.Alert = sev;
}
Thanks in advance!
Try adding a let clause to your query and define calculated field, like so:
var q = (from i in
(from x in context.Tickets
select new { x.OperatoreID, x.DataObiettivo })
group i by new { i.OperatoreID } into g
let nOperatore = context.Operatori
.Where(t => t.OperatoreID == e.OperatoreID)
.First().CognomeNomePuntato.ToString() &&
minutialla = context.Tickets
.Where(t => t.OperatoreID == e.OperatoreID)
.AsEnumerable().Min(a => a.MinutiAllaScadenza) &&
alert = context.Tickets
.Where(t => t.OperatoreID == e.OperatoreID)
.AsEnumerable().Min(a => a.Alert)
select new vmOperatoreDateObiettivo
{
OperatoreID = g.Key.OperatoreID,
NOperatore = nOperatore,
DataObiettivo = g.Max(d => d.DataObiettivo),
MinutiAllaScadenza = minutialla,
Alert = alert
}).ToList();

Linq orderby, can't work out how to use it

I have this function:
/// <summary>
/// Return array of all badges for a users
/// </summary>
public static Badge[] getUserBadges(int UserID)
{
Badge[] ReturnBadges;
using (MainContext db = new MainContext())
{
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => c.BadgeID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c });
ReturnBadges = new Badge[q.Count()];
int i = 0;
foreach (var UserBadge in q)
{
ReturnBadges[i] = new Badge(UserBadge.TheBadge.Key);
ReturnBadges[i].Quantity = UserBadge.BadgeCount;
i++;
}
}
return ReturnBadges;
}
I wish to order by tblBadges.OrderID ascending but I can't seem to find out where to put it, can anyone help?
I've tried:
.OrderBy(c=> c.TheBadge.OrderID)
But it's not valid code. TheBadge.Key in the loop is a tblBadges type. It's confusing me a bit why intellisense wont let me do the order by anywhere!
TheBadge isn't a single badge, it's a group of badges... so I'd personally rename it if I were you. Now, which OrderId do you want to get? You've got multiple entities in the gruop. For example, you could do this:
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => c.BadgeID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c })
.OrderBy(x => x.TheBadge.First().OrderId);
That will order by some notional "first" element - although I don't know what the generated SQL will look like.
If you expect the OrderId to be the same for every badge with the same ID, you might use:
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => new { c.BadgeID, c.OrderID })
.OrderBy(group => group.Key.OrderID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c });
Try this:
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => c.BadgeID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c.Key }) // *mod
.OrderBy(c=> c.TheBadge.OrderID); // * added
In the following line, TheBadge is a linq collection, not the badge itself. You want c.Key.
.Select(c => new { BadgeCount = c.Count(), TheBadge = c })

Categories

Resources