Linq with Left Join and multiples Key not Work - c#

I need help please!
When I perform the following LINQ query, it works perfectly (shows results)
using (var db = new MyEntities())
{
var result = (from dc in db.ClassDiary
where dc.DesTurm == dataForm.DesTurma
&& dc.Module == dataForm.Module
&& dc.CodDisc == dataForm.CdDisc
orderby dc.NrDiary
select new ClassDiaryMod
{
Id = dc.ID,
NrDiary = dc.NrDiary,
NrStudant = dc.NrStudant,
DesTurma = dc.DesTurma,
CdDisc = dc.CodDisc,
CdTeac = dc.CodTeac,
TotalFoult = (from f in db.Foult
where
f.NrStudant == dc.NrStudant &&
f.Disc == dc.CodDisc
select new FoultMod
{
Foults = f.Foult
}).Sum(x => x.Foults)
}).ToList();
return result;
When I try to apply the left join with multiple key does not display results
using (var db = new FamespEntities())
{
var result = (from dc in db.ClassDiary
join fn in db.Foult
on new { dc.NrStudant, dc.CodDisc, dc.DesTurm }
equals new { fn.NrStudant, CodDisc = fn.Disc, DesTurm = fn.Desturm } into fn_join
from fn in fn_join.DefaultIfEmpty()
where dc.DesTurm == dataForm.DesTurm
&& dc.Module == dataForm.Module
&& dc.CodDisc == dataForm.CdDisc
orderby dc.NroDiary
select new ClassDiaryMod
{
Id = dc.Id,
NrDiary = dc.NroDiary,
NrStudant = dc.NrStudant,
DesTurm = dc.DesTurm,
CdDisc = dc.CodDisc,
CdTeac = dc.CodTeac,
FoultOfDay = fn.Foult,
TotalFoults = (from f in db.Foult
where
f.NrStudent == dc.NrStudant &&
f.Disc == dc.CodDisc
select new FoultMod
{
Foults = f.Foult
}).Sum(x => x.Foults)
}).ToList();
Like to understand why the first code works and the second does not.
Thank you so much

Your equals
on new { dc.NrStudant, dc.CodDisc, dc.DesTurm }
equals new { fn.NrStudant, CodDisc = fn.Disc, DesTurm = fn.Desturm }
Is not correct, it should be
on new { NrStudant = dc.NrStudant, CodDisc = dc.CodDisc, DesTurm = dc.DesTurm }
equals new { NrStudant = fn.NrStudant, CodDisc = fn.Disc, DesTurm = fn.Desturm }
so field comparison could work.

Related

Linq query to get list inside list

Below is the query,
List<int> groupIdList = {1, 2};
var clientGroupData = from cge in base.context.Set<ClientGroupEngagement>()
join cg in base.context.Set<ClientGroup>() on cge.ClientGroupID equals cg.ClientGroupID
join cgu in base.context.Set<ClientGroupUser>() on cg.ClientGroupID equals cgu.ClientGroupID
join eng in base.context.Set<Engagement>() on cge.EngagementID equals eng.EngagementID
join cdc in base.context.Set<CountryDataCenter>()
on new { eng.CountryID, eng.EngagementVersion } equals new { cdc.CountryID, cdc.EngagementVersion }
join dc in base.context.Set<DataCenter>()
on cdc.DataCenterID equals dc.DataCenterID
join dcuri in base.context.Set<DataCenterURI>()
on new { dc.DataCenterID, cdc.EngagementVersion } equals new { dcuri.DataCenterID, dcuri.EngagementVersion }
join uritype in base.context.Set<URIType>()
on dcuri.URITypeID equals uritype.URITypeID
where groupIdList.Contains(cgu.ClientGroupID)
&& cg.IsActive
&& cdc.IsActive
&& dc.IsActive
&& dcuri.IsActive
&& uritype.IsActive
&& (dcuri.URITypeID == (int)URITypeEnum.WebUri || dcuri.URITypeID == (int)URITypeEnum.AppUri)
select new ClientGroupUserEngagementModel
{
EngagementId = cge.EngagementID,
EngagementDescription = eng.EngagementDescription,
EngagementStatusId = eng.EngagementStatusID,
ClientGroupId = cg.ClientGroupID,
ClientGroupGuid = cg.ClientGroupGUID,
ClientGroupName = cg.ClientGroupName,
UserId = cgu.ClientUserID,
FirstName = cgu.FirstName,
LastName = cgu.LastName,
IsGroupUserActive = cgu.IsActive,
LocatorDataModel = new LocatorDataModel
{
DatacenterId = cdc.DataCenterID,
DatacenterName = dc.DataCenterName,
EngagementVersion = cdc.EngagementVersion,
Uri = dcuri.URI,
UriTypeId = dcuri.URITypeID
},
};
var result = await clientGroupData.ToListAsync();
I am expecting list of LocatorDataModel in the result set. EngagementId is key which will be unique.
Currently it is pulling *2 records due to condition
(dcuri.URITypeID == (int)URITypeEnum.WebUri || dcuri.URITypeID == (int)URITypeEnum.AppUri)
How can get result like
Engagementid 1 : dataurl1 dataurl2
Engagementid 2: dataurl3 dataurl4, dataurl5
etc.
Any help is appreciated.
I think below sample code can help you:
var list = new[]
{
new { Engagementid = 1, Dataurl = "dataurl1"},
new { Engagementid = 1, Dataurl = "dataurl2"},
new { Engagementid = 2, Dataurl = "dataurl3"},
new { Engagementid = 2, Dataurl = "dataurl4"},
new { Engagementid = 2, Dataurl = "dataurl5"}
};
var result =
list.GroupBy(g => g.Engagementid)
.Select(c => new {Engagementid = c.Key, Dataurls = string.Join(",", c.Select(x=> x.Dataurl).ToList())})
.ToList();
That result will be:
[0]: { Engagementid = 1, Dataurls = "dataurl1,dataurl2" }
[1]: { Engagementid = 2, Dataurls = "dataurl3,dataurl4,dataurl5" }

Entity Framework no statements executed after query

So i'm using Quartz to create a task scheduler for my program and I'm having issues where if there are multiple jobs to run, it will repeatedly execute the query for the respective job but then never exectues the very next line. It's as if it hangs as soon as i hit tolist(). Any ideas?
try
{
//work on query further , need to get client ID correctly
if (vehicleses.Count == 0)
return null;
string siteId = QueryExportSiteWithId(exportSiteId).SiteId;
string clientId = vehicleses[0].ClientID;
db.Database.Log = Console.Write;
var inventoryyReturn = from i in db.Inventory_Vehicles
where dealerIdList.Any(c => c == i.ClientID) && i.Archived != "1" && i.Holding != "1" &&
i.Status == "A"
select i;
var inventoryDescription = from i in db.Inventory_Descriptions
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var settingsExports = from i in db.Settings_Exports
where inventoryyReturn.Any(c => c.ClientID == i.ClientID)
select i;
var settingLots = from i in db.Settings_Lots
where
inventoryyReturn.Any(
c => new {client = c.ClientID, lot = c.LotID} == new {client = i.ClientID, lot = i.ID})
select i;
var inventoryFeatures = from i in db.Inventory_Features
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var inventoryPhotos = from i in db.Inventory_Photos
where
inventoryyReturn.Any(c => c.ID == i.InventoryID)
select i;
var longReturnListt = (from i in inventoryyReturn
join l in inventoryDescription on new {inv = i.ID, cli = i.ClientID} equals
new {inv = l.InventoryID, cli = l.ClientID} into descGroup
from m in descGroup.DefaultIfEmpty()
join s in settingsExports on i.ClientID equals s.ClientID into settingGroup
from sg in settingGroup.DefaultIfEmpty()
join sl in settingLots on new {client = sg.ClientID, lot = sg.LotID} equals
new {client = sl.ClientID, lot = sl.ID} into lotsGroup
from lg in lotsGroup.DefaultIfEmpty()
join se in db.Settings_ExportSites on new {client = lg.ClientID, lotId = i.LotID, site = siteId}
equals new {client = se.ClientID, lotId = se.LotID, site = se.Site} into exportGroup
from eg in exportGroup.DefaultIfEmpty()
join f in inventoryFeatures on new {inv = i.ID, cli = i.ClientID} equals
new {inv = f.InventoryID, cli = f.ClientID} into invFeatGroup
from ifg in invFeatGroup.DefaultIfEmpty()
join p in inventoryPhotos on i.ID equals p.InventoryID into photo
from photos in photo.DefaultIfEmpty()
orderby i.ID
select new {i, m, sg, photoo = photo.ToList(), lg, ifg, eg}
into grouped
group grouped by new {grouped.i.ClientID}
into groupedDone
//select groupedDone
from categories in groupedDone
select new NewType
{
InventoryVehicles = categories.i,
InventoryDescriptions = categories.m,
SettingsExports = categories.sg,
InventoryPhotos = categories.photoo,
SettingsLots = categories.lg,
InventoryFeatures = categories.ifg,
SettingsExportSites = categories.eg
}
).ToList();
// var sql = ((System.Data.Entity.Core.Objects.ObjectQuery) longReturnListt as ObjectQuery);
// var trace = sql.ToTraceString();
if (longReturnListt != null)
{
//returnList.AddRange(longReturnListt.);
return returnList;
}
return null;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}

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();

This method is not supported against a materialized query result

Take a look at my code here:
public static ItemType GetItem(int id)
{
ItemType it = new ItemType();
using (var context = matrix2.matrix2core.DataAccess.Connection.GetContext())
{
var q = (from ci in context.Item
where ci.ID == id
let TemplateID = ci.TemplateID
let Groups = from x in context.CriteriaGroup
where x.TemplateID == TemplateID
select new
{
x
}
let CriteriaItems = from x in context.CriteriaItem
where Groups.Select(y => y.x.ID).Contains(x.CriteriaGroupID)
select new
{
x
}
select new
{
ci.ID,
ci.Name,
ci.CategoryID,
ci.Description,
ci.ItemValue,
TemplateID,
Groups,
CriteriaItems,
ItemValues = from x in context.ItemValue
where x.ItemID == id
select new
{
x,
CriteriaID = x.CriteriaItem.Criteria.ID
}
}).FirstOrDefault();
if (q != null)
{
it.ID = q.ID;
it.CategoryID = q.CategoryID;
it.Name = q.Name;
it.TemplateID = q.TemplateID;
it.Description = q.Description;
it.CriteriaGroups = new List<CriteriaGroupType>();
it.CriteriaItems = new List<CriteriaItemType>();
it.ItemValues = new List<ItemValueType>();
foreach (var x in q.ItemValues)
{
ItemValueType ivt = new ItemValueType();
ivt.CriteriaItemID = x.x.CriteriaItemID;
ivt.CriteriaID = x.CriteriaID;
ivt.Data = x.x.Data;
ivt.ID = x.x.ID;
ivt.ItemID = x.x.ItemID;
it.ItemValues.Add(ivt);
}
/////////error when I added the orderby clause
foreach (var x in q.Groups.OrderBy(x => x.x.SortOrder))
{
CriteriaGroupType cgt = new CriteriaGroupType();
cgt.ID = x.x.ID;
cgt.Name = !string.IsNullOrEmpty(x.x.Name) ? x.x.Name : "Group" + x.x.ID;
cgt.SortOrder = x.x.SortOrder;
cgt.TemplateID = x.x.TemplateID;
it.CriteriaGroups.Add(cgt);
}
/////////error when I added the orderby clause
foreach (var temp in q.CriteriaItems.OrderBy(x => x.x.SortOrder))
{
CriteriaItemType cit = new CriteriaItemType();
cit.ID = temp.x.ID;
cit.CriteriaGroupID = temp.x.CriteriaGroupID;
cit.GroupName = (temp.x.Name != null) ? temp.x.Name : "Group" + temp.x.ID;
cit.CriteriaID = temp.x.CriteriaID;
cit.CriteriaName = temp.x.Criteria.Name;
cit.Name = !string.IsNullOrEmpty(temp.x.Name) ? temp.x.Name : temp.x.Criteria.Name;
cit.Options = temp.x.Options;
it.CriteriaItems.Add(cit);
}
}
}
return it;
}
Instead of letting SQL handle the sorting (OrderBy) I wanted asp.net to do the sorting instead. I took the sorting out of the SQL linq query and put it on the foreach loop. When I did that I got the error. Is there a way to fix this?
You should be able to go from IQueryable to IEnumerable with a simple
var q2 = q.ToList();
What I meant of course was :
var groups = q.Groups.ToList();

Categories