Turning a MySQL query in LINQ SQL - c#

I'm trying to make a MySQL query in LINQ to SQL but I am with a doubt. How do I "Sum(0.5) as QtdeDias" in LINQ to SQL?
Query:
Select CL.NomeDeGuerra as Colaborador, '' as Gerente, 'Bloqueio' as Cliente, 'Bloqueio' as Frente,
Date_Format(A.DataReferencia, '%Y-%m-01 00:00:00') as Periodo, 'Bloqueio' as Atividade, Sum(0.5) as QtdeDias
From Agenda A
join Colaborador CL on (A.ColaboradorID = CL.ID)
Where CL.Socio = 0 and A.TipoAgenda = 2 and A.IsDeleted = 0 and CL.ID = 29
group by CL.NomeDeGuerra, Concat('BLOQUEIO-', A.Descricao), Date_Format(A.DataReferencia, '%Y/%m')
Linq to SQL:
var recursos = from a in this.Context.Agenda
join cl in this.Context.Colaborador on a.ColaboradorID equals cl.ID
where
cl.ID == colaboradorId
&& cl.Socio == 0
&& a.TipoAgenda == 2
&& !a.IsDeleted
group new { cl, a } by new { cl.NomeDeGuerra, a.Descricao, a.DataReferencia } into g
select new
{
FrenteProjetoID = 0,
Colaborador = g.Key.NomeDeGuerra,
Gerente = "",
Cliente = "Bloqueio",
Frente = "Bloqueio",
DataReferencia = g.Key.DataReferencia,
Atividade = "Bloqueio",
QtdeDias = (decimal)0.5 ???????
};
Thanks!

You can try using the grouping you've created.
select new
{
FrenteProjetoID = 0,
Colaborador = g.Key.NomeDeGuerra,
Gerente = "",
Cliente = "Bloqueio",
Frente = "Bloqueio",
DataReferencia = g.Key.DataReferencia,
Atividade = "Bloqueio",
QtdeDias = g.Sum(e => 0.5m)
};

Related

C# subquery in LINQ select

I'm trying to convert this query to LINQ, but I'm not getting the value of the subquery
QUERY:
select c.cod, c.cpfcnpj, c.razaosocial, c.nome, c.fone, c.celular, c.email, c.dtcad, s.dataval as validade,
(select max(datapagamento) from vendas where c.cod = coduser) as datapag
from usuarios c, libsys s
WHERE c.cod = s.codcli
and c.cod in (select coduser from vendas)
AND c.cod in (select l.codcli from libsys l where l.dataval >= current_date)
order by c.dtcad asc
LINQ:
var rel = await (from u in _contexto.usuarios
from v in _contexto.libsys
where (
(u.cod == v.codcli) &&
_contexto.vendas.Any(y => y.coduser == u.cod) &&
_contexto.libsys.Any(y => y.codcli == u.cod && y.pcpdataval >= System.DateTime.Now)
)
select new RelatorioLicsModel
{
cod = u.cod,
cpfcnpj = u.cpfcnpj,
razaosocial = u.razaosocial,
nome = u.nome,
fone = u.fone,
celular = u.celular,
email = u.email,
dtcad = u.dtcad,
validade = v.pcpdataval.ToString(),
dtpag = Convert.ToDateTime(_contexto.vendas.Where(s => s.datapagamento == _contexto.vendas.Max(x => x.datapagamento) && s.coduser == u.cod).FirstOrDefault())
}).ToListAsync();
the error I get is:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY v.coduser ORDER BY v.cod) AS row\r\n FROM vendas ' at line 7"}
is this the correct way to do this? thanks for any help!
Problem with dtpag property.
var query =
from u in _contexto.usuarios
from v in _contexto.libsys
where (
(u.cod == v.codcli) &&
_contexto.vendas.Any(y => y.coduser == u.cod) &&
_contexto.libsys.Any(y => y.codcli == u.cod && y.pcpdataval >= System.DateTime.Now)
)
select new RelatorioLicsModel
{
cod = u.cod,
cpfcnpj = u.cpfcnpj,
razaosocial = u.razaosocial,
nome = u.nome,
fone = u.fone,
celular = u.celular,
email = u.email,
dtcad = u.dtcad,
validade = v.pcpdataval.ToString(),
dtpag = Convert.ToDateTime(_contexto.vendas.Where(s => s.coduser == u.cod).Max(x => x.datapagamento))
}

COUNT(DISTINCT *) in ef core 2.1

SELECT
e.EmpName,
me.RemarkNumber,
me.RemarkPeopleNumber
FROM
EmployeeInfo e
LEFT JOIN (
SELECT
COUNT(RemarkId) As RemarkNumber,
COUNT(DISTINCT MemberId) As RemarkPeopleNumber,
CreateUser
FROM
MemberRemark
WHERE
RemarkStatus = 0
GROUP BY
CreateUser
) AS me On e.EmpName = me.CreateUser
WHERE
BranchCode = '0000'
And [Status] = 0
How to convert it to LINQ?
from e in db.EmployeeInfo
join me in (
from memberRemarks in db.MemberRemark
where memberRemarks.RemarkStatus == 0
group memberRemarks by new
{
memberRemarks.CreateUser,
} into g
select new
{
RemarkNumber = g.Count(),
RemarkPeopleNumber = g.Select(m => m.MemberId).Distinct().Count(),
g.Key.CreateUser
}
) on new { e.EmpName } equals new { EmpName = me.CreateUser } into meJoin
from me in meJoin.DefaultIfEmpty()
where e.BranchCode == "0000" & &e.Status == 0
select new
{
e.EmpName,
me.RemarkNumber,
me.RemarkPeopleNumber
};
I got this error
RemarkPeopleNumber = g.Select(m=>m.MemberId).Distinct().Count(),
//error
Using asp.net core mvc 2.1 + ef core 2.1 + mssql
Perhaps if you broke the query up into pieces it would be handled better? Using my SQL to LINQ Recipe I would translate your SQL like this:
var ePart = from e in db.EmployeeInfo
where e.BranchCode == "0000" && e.Status == 0
select e;
var mrPart = from mr in db.MemberRemark
where mr.RemarkStatus == 0
group mr by mr.CreateUser into mrg
select new {
CreateUser = mrg.Key,
RemarkNumber = mrg.Count(),
RemarkPeopleNumber = mrg.Select(mr => mr.MemberId).Distinct().Count()
};
var ans = from e in ePart
join me in mrPart on e.EmpName equals me.CreateUser into mej
from me in mej
select new {
e.EmpName,
me.RemarkNumber,
me.RemarkPeopleNumber
};

C# - LINQ - Sum a field from other table

I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto
Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.
This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,
var cuentas = (from mov in _data.Movimientos
join ct in _data.Cuentas
on mov.CuentasId equals ct.CuentasId
where ct.IsDeleted == 0 && mov.IsDeleted == 0
group ct by new
{
CuentasId = ct.CuentasId,
Alias = ct.Alias,
Moneda = ct.Monedas.Nombre,
Signo = ct.Monedas.Signo,
Banco = ct.Bancos.Nombre
} into ctg
select new
{
Alias = ctg.Key.Alias,
Moneda = ctg.Key.Moneda,
Signo = ctg.Key.Signo,
Banco = ctg.Key.Banco,
Monto = ctg.Sum(mov.Monto)
}
).ToList();
You need to group the value you want to sum like this
group mov.Monto by new { ..... } into ctg
Then ctg will be a collection of mov.Monto values grouped by your list of properties of ct and you'd just call Sum on ctg in your select
Monto = ctg.Sum()
So your new query would be
var cuentas = (from mov in _data.Movimientos
join ct in _data.Cuentas
on mov.CuentasId equals ct.CuentasId
where ct.IsDeleted == 0 && mov.IsDeleted == 0
group mov.Monto by new
{
CuentasId = ct.CuentasId,
Alias = ct.Alias,
Moneda = ct.Monedas.Nombre,
Signo = ct.Monedas.Signo,
Banco = ct.Bancos.Nombre
} into ctg
select new
{
Alias = ctg.Key.Alias,
Moneda = ctg.Key.Moneda,
Signo = ctg.Key.Signo,
Banco = ctg.Key.Banco,
Monto = ctg.Sum()
}).ToList();
You could also try grouping by first and then just summing the items later:
var cuentas = (from mov in _data.Movimientos.Where(w => w.IsDeleted == 0).GroupBy(g => g.CuentasId)
join ct in _data.Cuentas.Where(w => w.IsDeleted == 0).GroupBy(g => new { CuentasId = g.CuentasId, Alias = g.Alias, Monedas = g.Monedas.Nombre, Signo = g.Monedas.Signo, Banco = g.Bancos.Nombre })
on mov.Key.CuentasId equals ct.Key.CuentasId
select new
{
Alias = ct.Key.Alias,
Moneda = ct.Key.Moneda,
Signo = ct.Key.Signo,
Banco = ct.Key.Banco,
Monto = mov.Sum(s => s.Monto)
}
).ToList();

left join linq is not working

i have this linq query
var x = (from d in detalle
from n in nlj.DefaultIfEmpty()
join nd in nuevodetalle
on new { d.ope_idsku ,d.ope_tipo } equals new {nd.ope_idsku ,nd.ope_tipo }into nlj
from n in nlj.DefaultIfEmpty()
select new { d, n } ).ToList();
now if i do it
x[0].d==null this return false
x[0].n==null this return false
x[1].d==null this return false
x[1].n==null this fails, why?
my real select is not {d,n } it is
select new ope_detalle_autoventa()
{
CreatedOn = d.CreatedOn,
ModifiedOn = d.ModifiedOn,
ope_autoventaid = d.ope_autoventaid,
ope_Codope = d.ope_Codope,
ope_detalle_autoventaId = (tiene_nuevo_primarykey) ? Guid.NewGuid() : d.ope_detalle_autoventaId,
ope_entregado = (d.ope_entregado - (n != null ? n.ope_entregado : 0)),
ope_envase = d.ope_envase,
ope_estado = d.ope_estado,
ope_icono = d.ope_icono,
ope_idsku = d.ope_idsku,
ope_name = d.ope_name,
ope_pedido = d.ope_pedido,
ope_precioV = d.ope_precioV,
ope_prestamo = d.ope_prestamo,
ope_promocion = d.ope_promocion,
ope_skuid = d.ope_skuid,
ope_tipo = d.ope_tipo,
ope_autoventaidTarget = d.ope_autoventaidTarget,
ope_skuidTarget = d.ope_skuidTarget,
Ope_NumVenta = d.Ope_NumVenta,
ope_descuento = d.ope_descuento,
ope_cancelado = d.ope_cancelado,
ope_folio = d.ope_folio,
ope_cantcanc = 0,
ope_estimado = "0"
}
but this get fails same reason x[1].n==null fails, (that i believe),
i believe this fails at this line
ope_entregado = (d.ope_entregado - (n != null ? n.ope_entregado : 0)),
however
this query doesn't fail
var restaragregados = (from r in resultadoregresar
group new { r.ope_entregado } by new { r.ope_idsku } into agrupacion
select new { agrupacion.Key.ope_idsku, entregadototal=(agrupacion.Sum (x=> x.ope_entregado) ) }
);
List<ope_detalle_autoventa> nuevodetalle = (from d in detalle
join c in cargainventario
on d.ope_idsku equals c.ope_idsku into clj
from c in clj.DefaultIfEmpty()
join r in restaragregados on
d.ope_idsku equals r.ope_idsku into rlj
from r in rlj.DefaultIfEmpty ()
where (c!=null?c.ope_carga == cargausada:c==null )
&& (d.ope_entregado > ((c==null ?0:c.ope_disponibles ) - (r==null?0:r.entregadototal)))
&& d.ope_tipo ==tipos[i]
select new ope_detalle_autoventa()
{
ModifiedOn = DateTime.Now,
ope_autoventaid = ope_autoventaid,
ope_detalle_autoventaId = d.ope_detalle_autoventaId,
ope_entregado = (d.ope_entregado - ((c== null ? 0 : c.ope_disponibles) - (r == null ? 0 : r.entregadototal))),
ope_envase = d.ope_envase,
ope_estado = d.ope_estado,
ope_icono = d.ope_icono,
ope_idsku = d.ope_idsku,
ope_name = d.ope_name,
ope_pedido = 0,//0 por que no pidio de esta carga sino de la que ya se gastó
ope_precioV = d.ope_precioV,
ope_prestamo = d.ope_prestamo,
ope_promocion = d.ope_promocion,
ope_skuid = d.ope_skuid,
ope_tipo = d.ope_tipo,
ope_autoventaidTarget = d.ope_autoventaidTarget,
ope_skuidTarget = d.ope_skuidTarget,
Ope_NumVenta = d.Ope_NumVenta,
ope_descuento = d.ope_descuento,
ope_cancelado =d.ope_cancelado ,
CreatedOn =DateTime.Now ,
ope_Codope =d.ope_Codope ,
ope_folio =d.ope_folio,
ope_cantcanc =0,
ope_estimado="0"
}
).ToList();
i rename n by c and i change
on new { d.ope_idsku ,d.ope_tipo } equals new {nd.ope_idsku ,nd.ope_tipo }into nlj
by d.ope_idsku equals nd.ope_idsku into nlj
but i get the same error.
I solved with this
if (nuevodetalle.Count == 0)
nuevodetalle.Add(detalle [0]);
ope_detalle_autoventa clone = (ope_detalle_autoventa)detalle[0].Clone();
clone.ope_idsku = 0;
clone.ope_entregado = 0;
clone.ope_tipo = 0;
List<ope_detalle_autoventa> detallecargaactual = new List<ope_detalle_autoventa>();
var x = (
from d in detalle
join c in nuevodetalle
//on new { d.ope_idsku, d.ope_tipo } equals new { c.ope_idsku, c.ope_tipo } into clj
on d.ope_idsku equals c.ope_idsku into clj
from c in clj.DefaultIfEmpty (clone)
select new{ d, c}).ToList();`enter code here
you can see i changed clj.DefaultIfEmpty (clone)

Join LINQ with a List<> in select new

hi first time im asking here so il try to do it correctly
i have a problem im making a shopping basket and im nearly there but always a but
what i want to have is something like this
List<HKurv> KurvInnhold = (List<HKurv>)Session["KurvInnhold"];
DataClasses1DataContext db = new DataClasses1DataContext();
if (Session["KurvInnhold"] != null)
{
var query = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
d.VareKjøpt.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
BestiltAntall = d.AntallValgt,
Price = b.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query;
Handlekurv1.DataBind();
}
But it does not allow for usage of db and list<> in same query
Solved! Modified magnus's answer
var kjopKollonne = from p in KurvInnhold
select p.VareKjøpt;
var query1 = (from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
where
kjopKollonne.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}).ToList();
var query2 = from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();
Try this:
var query1 = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
KurvInnhold.Select(k => k.VareKjøpt).Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}.ToList();
var query2 =
from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();

Categories