LINq query throws exception - c#

I am running the following query
var allroles = from l in metaData.Role select l.RoleId;
var personroles = from k in metaData.PersonRole
where k.PersonId == new Guid(Session["user_id"].ToString())
select k.RoleId;
Dictionary<Guid, string> allroleswithnames =
(from l in metaData.Role
select new { l.RoleId, l.Description })
.ToDictionary(u => u.RoleId, u => u.Description);
var avl_roles = from j in allroles.Except(personroles)
select new
{
RoleId = j,
Description = allroleswithnames[new Guid(j.ToString())]
};
clist_avl_roles.DataSource = avl_roles;
clist_avl_roles.DataBind();
The code at code for avl_roles throwing error
Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Actually there are multiple rows for roleid with same person id. How do I rewrite the query to handle this situation?

var personId = new Guid(Session["user_id"].ToString());
var personRoles = metaData.PersonRole
.Where(pr => pr.PersonId == personId)
.Select(pr => pr.RoleId);
var avl_roles = from r in metaData.Role
where !personRoles.Contains(r.RoleId)
select new { r.RoleId, r.Description };
Or in single query
var avl_roles = from r in metaData.Role
join pr in metaData.PersonRole.Where(x => x.PersonId == personId)
on r.RoleId equals pr.RoleId into g
where !g.Any()
select new { r.RoleId, r.Description };

Related

if control in linq?

This query is what I got:
var hede = (from customer in _customerRepository.Table
join source in _sourcedefinitionepository.Table on customer.SourceCode equals source.SourceCode
select new {Customer = customer, source.SourceName}
And then I wrote this:
if (agencyName ! = null )
hede = hede.Where(p => p.Customer.Name.StartsWith(agencyName));
How can i put the if code into first part of code?
You can achieve it in this way
where agencyName == null || customer.Name.StartsWith(agencyName));
Full query
var hede = (from customer in _customerRepository.Table
join source in _sourcedefinitionepository.Table on customer.SourceCode equals source.SourceCode
where agencyName == null || customer.Name.StartsWith(agencyName))
select new {Customer = customer, source.SourceName}
Updated
Using lamda.
var hede = _customerRepository.Table.Join(_sourcedefinitionepository.Table, c => c.SouceCode , s => s.SourceCode,
(c, s) => new
{
Customer = c,
s.SourceName
})).Where(p => agencyName == null || p.Customer.Name.StartsWith(agencyName)).ToList();
You can use the following code
var hede = _customerRepository.Table.Join(_sourcedefinitionepository.Table,
x => x.SourceCode,
y => y.SourceCode,
(customer, source) => new { customer, source.SourceName})
.Where(p => agencyName == null ||
(p.customer.Name.Any(f => p.customer.Name.StartsWith(agencyName))));
lambda code
var hede =from customer in _customerRepository.Table
join source in _sourcedefinitionepository.Table
on customer.SourceCode equals source.SourceCode
where agencyName == null || customer.Name.Any(f => customer.Name.StartsWith(agencyName))
select new { Customer = customer, source.SourceName };

Yet another “A query body must end with a select clause or a group clause”

This query does work, but I am trying to combine the two steps into one query.
var query1 = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>()
.Where
(u =>
u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office)
)
select new
{
hOffice = o.Name,
bName = u.Name
};
var query2 = query1.GroupBy(t => new { office = t.hOffice, name = t.bName })
.Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() });
If I try to combine the two queries using the following query it gives me the “A query body must end with a select clause or a group clause” error.
var query1 = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>()
.Where
(u =>
u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office)
)
.GroupBy(t => new { office = t.Office, name = t.Name })
.Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() });
I think I have to add a select something, but I can't figure out what.
Can anyone please help?
Your query must contain a select clause. The .Where(...).GroupBy(...).Select(...) are only on the db.GetTable<Users>(). Something like:
var query1 = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>().Where(u => u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office))
.GroupBy(t => new { office = t.Office, name = t.Name })
.Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() })
select new { /* Desired properties */};
But I think you are looking for something like:
var result = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>()
where u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office))
group 1 by new { t.Office, t.Name } into g
select new { Office = g.Key.Office, Name = g.Key.Name, Count = g.Count() };

Primitive type error in LINQ to SQL query+subquery

I got the famous "only primitive types or enumeration types..." error, and I cannot find the solution.
This is the code that is making my head explode (it's part of a select in another LINQ code):
Min = (from inddetails in EntitiesDB.ConfSet
where (final.Max(x => x.hosp.Hos_NumOnc) > inddetails.Conf_Desde && final.Max(x => x.hosp.Hos_NumOnc) < inddetails.Conf_Hasta)
|| final.Max(x => x.hosp.Hos_NumOnc) > (from inddetails2 in EntitiesDB.ConfSet select inddetails2.Conf_Hasta).Max()
select inddetails.Conf_NumeroRegistros)
Here is the full code as requested with the last updates (nothing changed):
var result = from indicadores in EntitiesDB.Catalogo_IndicadoresSet
join crit in EntitiesDB.Catalogo_CriteriosSet on indicadores.CodigoCriterio equals crit.CodigoCriterio
join dimen in EntitiesDB.Catalogo_DimensionSet on crit.CodigoDimension equals dimen.CodigoDimension
join grupo in EntitiesDB.Catalogo_GruposSet on dimen.CodigoGrupo equals grupo.CodigoGrupo
join indicador_resultado in EntitiesDB.Catalogo_Indicador_ResultadoSet.DefaultIfEmpty() on indicadores.CodigoIndicador equals indicador_resultado.CodigoIndicador /*into joined
from j in joined.DefaultIfEmpty()*/
join user in EntitiesDB.UsuariosSet on indicador_resultado.CodigoUsuario equals user.CodigoUsuario
join hosp in EntitiesDB.HospitalesSet on user.CodigoHospital equals hosp.CodigoHospital
join hosper in EntitiesDB.Rel_Hospital_PeriodoSet on hosp.CodigoHospital equals hosper.CodigoHospital
join period in EntitiesDB.PeriodosSet on hosper.CodigoPeriodo equals period.CodigoPeriodo
where period.CodigoPeriodo == periodos.CodigoPeriodo
group new { indicadores, hosper, hosp, grupo, crit, dimen, indicador_resultado, user, period } by new { hosper.CodigoPeriodo, hosp.CodigoHospital, grupo.CodigoGrupo, indicadores.CodigoIndicador, period.Per_Nombre, hosp.Hos_Nombre, hosp.Hos_NumeroOncologos, grupo.Gru_Descripcion, indicador_resultado.CodigoResultado, indicador_resultado.Resul_Completado, indicador_resultado.Resul_Numerador, indicador_resultado.Resul_Denominador, indicador_resultado.Resul_Valor, indicador_resultado.Resul_Objetivo, indicador_resultado.Resul_Variacion, indicador_resultado.Resul_Detalle, indicador_resultado.Resul_Fecha, indicadores.Ind_Descripcion, dimen.CodigoDimension, crit.CodigoCriterio } into final
orderby final.Key.CodigoPeriodo, final.Key.CodigoHospital, final.Key.CodigoGrupo
select new
{
CodigoPeriodo = final.Key.CodigoPeriodo,
NombrePeriodo = final.Key.Per_Nombre,
CodigoHospital = final.Key.CodigoHospital,
NombreHospital = final.Key.Hos_Nombre,
NumeroOncologos = final.Key.Hos_NumeroOncologos),
CodigoGrupo = final.Key.CodigoGrupo,
NombreGrupo = final.Key.Gru_Descripcion,
CodigoResultado = final.Max(x => x.indicador_resultado.CodigoResultado),
Completado = final.Key.Resul_Completado,
Numerador = final.Max(x => x.indicador_resultado.Resul_Numerador),
Denominador = final.Max(x => x.indicador_resultado.Resul_Denominador),
Valor = final.Max(x => x.indicador_resultado.Resul_Valor),
Objetivo = final.Max(x => x.indicador_resultado.Resul_Objetivo),
Variacion = final.Max(x => x.indicador_resultado.Resul_Variacion),
Detalle = final.Key.Resul_Detalle,
CodigoIndicador = final.Key.CodigoIndicador,
NombreIndicador = final.Key.Ind_Descripcion,
CodigoDimension = final.Max(x => x.dimen.CodigoDimension),
CodigoCriterio = final.Max(x => x.crit.CodigoCriterio),
CasosMinimos = (from inddetalle in EntitiesDB.Configuracion_IndicadoresDetalleSet
where (final.Key.Hos_NumeroOncologos > inddetalle.Conf_Desde && final.Key.Hos_NumeroOncologos < inddetalle.Conf_Hasta)
|| final.Key.Hos_NumeroOncologos) > valorMaximo
select inddetalle.Conf_NumeroRegistros)
};
Take the max value out of the query:
var finalMax = final.Max(x => x.hosp.Hos_NumOnc);
Min = (from inddetails in EntitiesDB.ConfSet
where (finalMax > inddetails.Conf_Desde
&& finalMax < inddetails.Conf_Hasta)
|| finalMax > (from inddetails2 in EntitiesDB.ConfSet select inddetails2.Conf_Hasta).Max()
select inddetails.Conf_NumeroRegistros);
final is a collection of (non-primitive) objects, for which there is no SQL equivalent. It's also more efficient to do it this way.

SQL query to LINQ conversion with nested select statements

I want to convert the following query to LINQ:
SELECT LV.* FROM LowerVehicles LV
INNER JOIN (Select VSerial,MAX(updatedOn) MaxUpdatedOn from LowerVehicles group by vserial) LVG
ON LV.VSerial = LVG.VSerial AND LV.updatedOn = LVG.MaxUpdatedOn
Not knowing your entities classes, here is an approximation. You can use query syntax or fluent syntax. Sometimes one is preferable over the other, and in the case of joins and grouping I prefer to use query syntax.
QUERY SYNTAX
var query = from LV in LowerVehicles
join LVG in (
from r in LowerVehicles
group r by r.vserial into g
select new {VSerial = g.Key, MaxUpdatedOn = g.Max(t => t.updatedOn)})
on LV.VSerial equals LVG.Vserial
and LV.updatedOn equals LVG.MaxUpdatedOn
select LV;
FLUENT SYNTAX
var lvg = LowerVehicles.GroupBy(t => t.vserial)
.Select(g => new {
VSerial = g.Key,
MaxUpdatedOn = g.Max(t => t.updatedOn)
});
var query = LowerVehicles.Join(
lvg,
a => new { a.VSerial, a.updatedOn },
b => new { b.VSerial, b.MaxUpdatedOn },
(a, b) => new { LV = a, LVG = b}
)
.Select(t=> t.LV);
Something like this?
Something.LowerVehicles
.Join(something.LowerVehicles.Select(y => new { y.VSerial, updatedOn = y.updatedOn.Max() }).GroupBy(z => z.VSerial),
x => new { x.VSerial, x.updatedOn },
lvg => new { lvg.VSerial, lvg.updatedOn },
(x, y) => x)

Combining Tables without JOIN using Lambda Expression

Combining Tables without JOIN keyword
var res2 = from u in dtEmp.AsEnumerable()
from v in dtDept.AsEnumerable()
where u.Field<int>("DepartmentID") == v.Field<int>("DepartmentID") &&
u.Field<double>("Salary") > 10000
select new
{
Name = u.Field<string>("Name"),
Department = v.Field<string>("DepartmentName")
};
How to do the same using Lambda Expression without using Join Keyword?
Do you mean you want to switch from SQL syntax to Method Chain syntax? i.e:
var res2 = dtEmp.AsEnumerable()
.SelectMany(u => dtDept.AsEnumerable(), (u, v) => new {u, v})
.Where(#t => u.Field<int>("DepartmentID") == v.Field<int>("DepartmentID") &&
u.Field<double>("Salary") > 10000).Select(#t => new
{
Name = u.Field<string>("Name"),
Department = v.Field<string>("DepartmentName")
});

Categories