The Version field subselect in the where caluse is causing an out of memory error. If I remove it then the query works fine. The user profile table has multiple entries for each version and I only want the most recent in the final query results. Any ideas on how to make this query work without getting an out of memory error?
var x = (from p in userProfileRepo.All
join u1 in userRepo.All on p.USERID equals u1.USERID
join u2 in userRepo.All on p.LAST_MODIFIED_BY equals u2.USERID
join a in attrRepo.All on new { p.GROUP_NAME, p.PROFILE_NAME } equals new { a.GROUP_NAME, a.PROFILE_NAME } into attrJoin
from sub_a in attrJoin.DefaultIfEmpty()
where p.VERSION == (from up in userProfileRepo.All
where up.GROUP_NAME == p.GROUP_NAME
&& up.PROFILE_NAME == p.PROFILE_NAME
&& up.USERID == p.USERID
group up by up.VERSION into g
select g.Max(t => t.VERSION)).FirstOrDefault()
select new
{
GroupName = p.GROUP_NAME,
Author = u1.FIRSTNAME + #"\" + u1.LASTNAME,
LastModifiedBy = u2.FIRSTNAME + #"\" + u2.LASTNAME,
ProfileName = p.PROFILE_NAME,
Version = p.VERSION,
GroupName2 = (sub_a == null ? "" : sub_a.GROUP_NAME),
AttrName = (sub_a == null ? "" : sub_a.ATTR_NAME),
AttrDisplayName = (sub_a == null ? "" : sub_a.ATTR_DISPLAY_NAME),
AttrValue = (sub_a == null ? "" : sub_a.ATTR_VALUE),
Visible = (sub_a == null ? "" : sub_a.VISIBLE)
}).ToList();
Related
I need to join List of string into string inside linq select.
I tried that:
var myEnt = from p in ctx.Project
select new ProjectRepository.Project
{
Id = p.ProjectId,
Desc = p.ProjectDesc,
UsersProject = String.Join("; ", (
from up in ctx.usersProject join u in ctx.users
on up.user equals u.id into uloj from uj in uloj.DefaultIfEmpty()
where (up.deleted ?? false) == false
&& up.projectId == p.Id
&& (uj.deleted ?? false) == false
select uj.name + " " + uj.surname).ToList())
});
gridProg.DataSource = myEnt.ToList();
gridProg.DataBind();
But i had this error:
Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList(). For ASP.NET WebForms you can bind to the result of calling ToList() on the query or use Model Binding, for more information see http://go.microsoft.com/fwlink/?LinkId=389592.
Thank you.
UPDATE
New error after adding .Tolist() to DataSource binding.
LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
I have not tested it, but it will work. Make 2 different Queries
var Projects = (from up in ctx.usersProject join u in ctx.users
on up.user equals u.id into uloj from uj in uloj.DefaultIfEmpty()
where (up.deleted ?? false) == false
&& up.projectId == p.Id
&& (uj.deleted ?? false) == false
select new {
ProjectId = up.projectId,
ProjectsList = uj.name + " " + uj.surname
}).ToList();
var myEnt = from p in ctx.Project.AsEnumerable()
select new ProjectRepository.Project
{
Id = p.ProjectId,
Desc = p.ProjectDesc,
UsersProject = String.Join("; ", Projects.Where(e=> p.ProjectId == e.ProjectId).Select(e=> e.ProjectsList).ToList())
}).ToList();
I found the solution. I post the code below:
var usersProject = (from up in ctx.usersProject join u in ctx.users
on up.user equals u.id into uloj from uj in uloj.DefaultIfEmpty()
where (up.deleted ?? false) == false
&& up.projectId == p.Id
&& (uj.deleted ?? false) == false
select new {
ProjectId = up.projectId,
User = uj.name + " " + uj.surname
}).ToList();
var myEnt = from p in ctx.Project.AsEnumerable()
select new ProjectRepository.Project
{
Id = p.ProjectId,
Desc = p.ProjectDesc
}).ToList();
var myEntL = myEnt.ToList();
foreach (var mysingleEnt in myEntL)
{
myEntL.Where(x => x.Id == mysingleEnt.Id).FirstOrDefault().utentiAssociati =
String.Join("; ", usersProject
.Where(x => x.ProjectId == mysingleEnt.Id).Select(x => x.User).ToList());
}
gridProg.DataSource = myEntL;
gridProg.DataBind();
Thank you for help.
I have a rather ugly query that just had to be expanded by one more join. The query builds then throws a NullReferenceException runtime. As I'm struggling around the exception details I found the message at TargetSite/CustomAttributes/Message = "The method or operation is not implemented." But I don't know which method?
MarkedItems is the new join and I think the problem could be the join on multiple columns or that I had to add the new table into the group by clause. The same query runs in LinqPad with EF6, so this must be something that hasn't been implemented in EF7 yet.
EF Core version is 1.1.2.
The query:
var inventory = (from it in _ctx.Items
join i in _ctx.Inventories on it.Id equals i.ItemId into iit
from i in iit.DefaultIfEmpty()
join m in _ctx.MarkedItems on
new {
eancode = i.EANCode,
projectid = i.ProjectId
}
equals new {
eancode = (m != null ? m.EANCode : string.Empty),
projectid = (m != null ? m.ProjectId : Guid.Empty)
} into im
from m in im.DefaultIfEmpty()
where it.ProjectId == cmp.ProjectId
group i by new {
EANCode = it.EANCode,
ItemNo = it.ItemNo,
Name = it.Name,
BaseQty = it.BaseQty,
Price = it.Price,
m = (m != null ? m.EANCode : null)
} into lg
select new ComparisonBaseModel() {
EANCode = lg.Key.EANCode,
ItemName = lg.Key.Name,
Price = lg.Key.Price,
ScanQty = lg.Sum(s => s != null ? s.ScanQty : 0),
BaseQty = lg.Key.BaseQty,
DiffQty = lg.Sum(s => s != null ? s.ScanQty : 0) - lg.Key.BaseQty,
DiffPrice = lg.Key.Price * (lg.Sum(s=> s!= null ? s.ScanQty : 0) - lg.Key.BaseQty),
AllTasked = !lg.Any(s=>(s != null && s.InventoryTaskId == null) || s==null),
Flagged = lg.Key.m != null
}).Where(x=>x.DiffQty != 0);
Thanks to the comments I was able to find out the real problem with my query. I hadn't realized before, that Inventories (i) could be null, too, so I had to check for nulls even the i-s (not only m-s) in MarketItems join.
Not sure if this could be helpful to anyone but the error message was misleading after I have already run into some EF7/EF6 differences.
var inventory = (from it in _ctx.Items
join i in _ctx.Inventories on it.Id equals i.ItemId into iit
from i in iit.DefaultIfEmpty()
join m in _ctx.MarkedItems on
new {
eancode = (i != null ? i.EANCode : string.Empty),
projectid = (i != null ? i.ProjectId : Guid.Empty)
}
equals new {
eancode = (m != null ? m.EANCode : string.Empty),
projectid = (m != null ? m.ProjectId : Guid.Empty)
} into im
from m in im.DefaultIfEmpty()
where it.ProjectId == cmp.ProjectId
group i by new {
EANCode = it.EANCode,
ItemNo = it.ItemNo,
Name = it.Name,
BaseQty = it.BaseQty,
Price = it.Price,
m = (m != null ? m.EANCode : null)
} into lg
select new ComparisonBaseModel() {
EANCode = lg.Key.EANCode,
ItemName = lg.Key.Name,
Price = lg.Key.Price,
ScanQty = lg.Sum(s => s != null ? s.ScanQty : 0),
BaseQty = lg.Key.BaseQty,
DiffQty = lg.Sum(s => s != null ? s.ScanQty : 0) - lg.Key.BaseQty,
DiffPrice = lg.Key.Price * (lg.Sum(s=> s!= null ? s.ScanQty : 0) - lg.Key.BaseQty),
AllTasked = !lg.Any(s=>(s != null && s.InventoryTaskId == null) || s==null),
Flagged = lg.Key.m != null
}).Where(x=>x.DiffQty != 0);
I have two datatables,
var userList1 = from myRow in dt.AsEnumerable()
where myRow.Field<bool?>("IsActive1") == null
? true
: myRow.Field<bool?>("IsActive1") == true
select myRow;
var userList2 = from myRow in dt1.AsEnumerable()
select myRow;
dt1 table shows like this,
Using this Linq query,
var objUserSetUp1 = (from A in userList1
join B in userList2
on new
{
UserId = A.Field<Int64?>("Id") == null
? 0
: A.Field<Int64>("Id")
}
equals new
{
UserId = B.Field<Int64?>("UserId") == null
? 0
: B.Field<Int64>("UserId")
}
select new
{
UserId = A.Field<Int64>("Id"),
FirstName = A.Field<string>("FirstName"),
SurName = A.Field<string>("SurName"),
Computer_Name = A.Field<string>("Computer_Name"),
IP_Address = A.Field<string>("IP_Address"),
LogInTime = A.Field<string>("LogInTime") == null
? "UnKnown"
: A.Field<string>("LogInTime"),
UserName = A.Field<string>("UserName"),
Password = A.Field<string>("Password"),
login_Id = A.Field<Int64?>("login_Id") == null
? 0 :
A.Field<Int64?>("login_Id"),
docCount = B.Field<Int64>("docCount")
}).ToList();
How can I get if UserId is null also want to take docCout field value too. How can I do this inside the query?
I think you need a Left Outer Join, where the default value for the outer join (ie when no matching record exists) is the userList2 entry where Field("UserId") is null.
See below (untested, but you get the idea!):
var objUserSetUp1 = (from A in userList1
join B in userList2
on A.Field<Int64?>("Id") equals B.Field<Int64?>("UserId")
into BGroup
from C in BGroup.DefaultIfEmpty(userList2.Single(u => u.Field<Int64?>("UserId") == null))
select new
{
UserId = A.Field<Int64>("Id"),
FirstName = A.Field<string>("FirstName"),
SurName = A.Field<string>("SurName"),
Computer_Name = A.Field<string>("Computer_Name"),
IP_Address = A.Field<string>("IP_Address"),
LogInTime = A.Field<string>("LogInTime") == null
? "UnKnown"
: A.Field<string>("LogInTime"),
UserName = A.Field<string>("UserName"),
Password = A.Field<string>("Password"),
login_Id = A.Field<Int64?>("login_Id") == null
? 0 :
A.Field<Int64?>("login_Id"),
docCount = C.Field<Int64>("docCount")
}).ToList();
I have the following LINQ sentence
var MercanciasOperativo = from p in db.PLInformacionVerificacionTrasportes
join abogado in db.Constancias on p.AbogadoResponsable equals abogado.Id into abogadoGroup
from abogado in abogadoGroup.DefaultIfEmpty()
join oficio in db.Oficios on p.NumOrden equals oficio.Expediente into oficioGroup
from oficio in oficioGroup.DefaultIfEmpty()
join oficioviejo in db.Oficios0908 on p.NumOrden equals oficioviejo.NumOrden into oficioViejoGroup
from oficioviejo in oficioViejoGroup.DefaultIfEmpty()
join objPAD in db.MercanciasPuestoDisposicion on p.NumOrden equals objPAD.NumOficio into objPADGroup
from objPAD in objPADGroup.DefaultIfEmpty()
join agencia in db.Agencia on objPAD.Agencia equals agencia.Id into agenciaGroup
from agencia in agenciaGroup.DefaultIfEmpty()
join subsede in db.Subsedes on agencia.SubsedeId equals subsede.Id into subsedeGroup
from subsede in subsedeGroup.DefaultIfEmpty()
join inicio in db.VTInformacionVerificacionTrasportes on p.NumOrden equals inicio.NumOrden into
inicioGroup
from inicio in inicioGroup.DefaultIfEmpty()
join conceptoMulta in db.PLConceptoMultas on p.ConceptoMulta equals conceptoMulta.Id into
conceptoGroup
from conceptoMulta in conceptoGroup.DefaultIfEmpty()
join conceptoMultaRegularizacion in db.PLConceptoMultas on p.ConceptoMultaRegularizacion equals
conceptoMultaRegularizacion.Id into conceptoRegularizacionGroup
from conceptoMultaRegularizacion in conceptoRegularizacionGroup.DefaultIfEmpty()
join notificacion in db.PLNotificaciones on p.TipoNotificacion equals notificacion.Id into
notificacionGroup
from notificacion in notificacionGroup.DefaultIfEmpty()
join resolucion in db.PLTipoResolucion on p.TipoResolucion equals resolucion.Id into resolucionGroup
from resolucion in resolucionGroup.DefaultIfEmpty()
join ciudad in db.Ciudades on p.Ciudad equals ciudad.Id into ciudadGroup
from ciudad in ciudadGroup.DefaultIfEmpty()
let Loc = ciudad.Nombre
join multaExtra in
(from p in db.PLMultasExtra
group new {p.NumOrden, p.Monto}
by new {p.NumOrden}
into grp
select new
{
NumOrden = grp.Key.NumOrden,
cantidad = grp.Sum(x => x.Monto)
}
)
on p.NumOrden equals multaExtra.NumOrden into multaExtraGroup
from multaExtra in multaExtraGroup.DefaultIfEmpty()
where(oficio.StatusExpedienteN != 3 && oficio.StatusExpedienteN != 4 && oficio.StatusExpedienteN != 2 &&oficio.StatusExpedienteN != 7) && (inicio.HuboEmbargo)
select new
{
p.Id,
p.NumOrden,
OrdenVieja = oficioviejo.NumOrdenViejo ?? p.NumOrden,
FechaEmisionOrden = oficio.FechaOficio,
OficioProgramacion = oficio.NumOficio,
p.UbicacionArchivoTramite,
FechaNotificacionOrden = inicio.FechaNotificacionOrden,
FechaLevantamientoActa = inicio.FechaLevantamientoActa,
FechaEntregaPAMA = inicio.FechaEntregaPAMA,
FechaNotificacionPAMA = inicio.FechaNotificacionActa,
p.NumExpedientePAMA,
NumExpedientePuestoADisposicion = objPAD.NumExpedientePuestoADisposicion,
AbogadoResponsable = abogado.Nombre,
p.FechaAsignacion,
p.FechaIntegracion,
p.Plazo4Meses,
IDSelector = oficio.IDSelector,
IDSUI = oficio.IDSUI,
NombreTenedor = inicio.NombreTenedor,
NombreTenedor2 = inicio.NombreTenedor2,
ApellidoPaternoTenedor = inicio.ApellidoPaternoTenedor,
ApellidoMaternoTenedor = inicio.ApellidoMaternoTenedor,
Descripcion = inicio.Descripcion_Final.Substring(0, 1000),
p.NombreAquienSeEmite,
p.NombreAquienSeEmite2,
p.ApellidoPaternoAquienSeEmite,
p.ApellidoMaternoAquienSeEmite,
p.FechaNacimientoAquienSeEmite,
p.Rfc,
TieneMedioDeDefensa = db.PLMediosDefensa.Any(x => x.NumOrden == p.NumOrden) ? "Si" : "No",
TieneLiberacion = db.PLLiberacion.Any(x => x.NumOrden == p.NumOrden) ? "Si" : "No",
TieneAdjudicacion = db.PLAdjudicaciones.Any(x => x.NumOrden == p.NumOrden) ? "Si" : "No",
TieneCumplimentacion = db.PLResolucionesComplementarias.Any(x => x.NumOrden == p.NumOrden) ? "Si" : "No",
p.Calle,
p.NumDomicilio,
p.Interior,
p.Colonia,
Ciudad = ciudad.Nombre,
p.CP,
p.VAM,
p.VAMAproximado,
p.VAMResolucionPama,
MontoCreditoSinRedondear =
p.IGI + p.IGIActualizado + p.IGIRecargos + p.IVA + p.IVARecargos + p.IVAActualizado +
p.Multa + p.ValorComercial183_A_LA + p.IEPS + p.IEPSActualizado + p.IEPSRecargos + p.CC +
p.CCActualizado + p.CCRecargos + (multaExtra.cantidad ?? 0),
p.IGI,
p.IGIActualizado,
p.IGIRecargos,
p.IEPS,
p.IEPSActualizado,
p.IEPSRecargos,
p.IVA,
p.IVAActualizado,
p.IVARecargos,
p.CC,
p.CCActualizado,
p.CCRecargos,
p.Multa,
ConceptoMulta = conceptoMulta.ConceptoMulta,
p.ValorComercial183_A_LA,
multaExtra = multaExtra.cantidad ?? 0,
tieneRegularizacion = p.tieneRegularizacion ? "Si" : "No",
p.MultaRegularizacion,
ConceptoMultaRegularizacion = conceptoMultaRegularizacion.ConceptoMulta,
Condonacion = p.Condonacion ? "Autorizada" : "Negada",
p.SolicitudCondonacion,
p.FechaPresentacion,
p.OficioResolucion,
p.FechaOficioResolucion,
p.NotificacionResolucion,
p.OficioNotificacion,
TipoNotificacion = notificacion.Nombre,
TipoResolucion = resolucion.TipoResolucion,
p.Plazo45Dias,
tieneAutoCorreccion = p.tieneAutoCorreccion ? "Si" : "No",
IdPuestoADisposicion = oficio.idPuestoADisposicion,
Subsede = Loc,
tieneVerificacion = p.Verificado ? "Si" : "No",
p.Modifico
};
I know the query could be expensive but i really need all the fields, the problem is in design mode (while Im in visual studio IDE) I start debbuging and it works fine and relatively fast! , but when I publish it in IIS it shows me the next error:
And if I try to debug it as the message says:
Im confused because if exists an error it would occur from the desing mode, right?
The file output is above 1mb size. Could be a IIS configuration ?
I have two LinqToSql queries that return result sets:
var grResults = (from g in ctx.GeneralRequests
join rt in ctx.RequestTypes on g.RequestTypeId equals rt.RequestTypeId
join sub in ctx.Logins on g.SubmitterStaffId equals sub.LoginId
join onb in ctx.Logins on g.OnBehalfOfStaffId equals onb.LoginId
where sub.GadId == gadId
select new
{
Status = "Submitted",
RequestId = g.GeneralRequestId,
Submitter = sub.UserName,
OnBehalf = (onb == null ? string.Empty : onb.UserName),
RequestType = (rt == null ? string.Empty : rt.Description),
ProjectName = (g == null ? string.Empty : g.ProjectName) ,
Comments = (g == null ? string.Empty : g.Comments),
LastUpdate = g.LastUpdateDate
});
var grdResults = (from gd in ctx.GeneralRequestDrafts
join rt in ctx.RequestTypes on gd.RequestTypeId equals rt.RequestTypeId
into tempRequestTypes
from rt1 in tempRequestTypes.DefaultIfEmpty()
join onb in ctx.Logins on gd.OnBehalfOfStaffId equals onb.LoginId
into tempOnBehalf
from onb1 in tempOnBehalf.DefaultIfEmpty()
join sub in ctx.Logins on gd.SubmitterStaffId equals sub.LoginId
where sub.GadId == gadId
select new
{
Status = "Draft",
RequestId = gd.GeneralRequestDraftId,
Submitter = sub.UserName,
OnBehalf = (onb1 == null ? string.Empty : onb1.UserName),
RequestType = (rt1 == null ? string.Empty : rt1.Description),
ProjectName = (gd.ProjectName == null ? string.Empty : gd.ProjectName),
Comments = (gd.Comments == null ? string.Empty : gd.Comments),
LastUpdate = gd.LastUpdateDate
});
The problem is when I try to Union them.
var results = grResults.Union(grdResults).OrderByDescending(r => r.LastUpdate);
This returns no records even though the two individual queries do.
Since the 2 queries don't appear to rely on each other just execute both and union the results of each if you are just trying to get a single list.
var results = grResults.ToList().Union(grdResults.ToList())
.OrderByDescending(r => r.LastUpdate);