How to hide a row using LINQ C# - linq

I have a var variable where it has set of objects. I want to query a particular object and hide/delete 2 rows based on ID.
I am trying to select the value as below but still it is not working. Any help is greatly appreciated.
var getTransformDetails = contentView.Package; if(totalCost > 100000) { getTransformDetails.AnnualPaymentGrid.Where(x => x.Id != XXXXX1 || x.Id != XXXXX2); }

Related

Linq request group by

I'd like to group my request by FkOperateur and FkPstStd but I still need information in the select new part. How should I proceed to get IdPoste, FkStandard, IsValidated, Date depending on the group part result
var shortFormations =
(from f in _context.Formations
where f.FkPstStdNavigation.FkPosteNavigation.FkZoneNavigation.FkBatimentNavigation.IdBatiment == Batiment && (f.FkOperateurNavigation.Equipe == Equipe || Equipe == null)
group f by new { f.FkOperateur, f.FkPstStd } into formation
select new shortFormations
{
FkOperateur = formation.Key.FkOperateur,
FkPstStd = formation.Key.FkPstStd,
IdPoste = f.FkPstStdNavigation.FkPosteNavigation.IdPoste,
FkStandard = f.FkPstStdNavigation.FkStandard,
IsValidated = f.IsValidated,
Date = f.DateFormation,
})
.AsNoTracking()
.ToList();
I can't get IdPoste FkStandard IsValidated and Date
return f doesn't exist on current context on these line.
Could you explain me please.
Select
fk_operateur,Fk_Pst_Std, max(date_formation)
FROM
Formations
GROUP by
Fk_Operateur,Fk_Pst_Std
that's a try in SQL but I'm not able to get others column mentionned before
returns
fk_operateur
FkPstStd
date_formation
1
1
Adate
and many other rows
Since its grouped, to access the mentioned fields, you will have to look in the Values and select the correct item. As in, something like
select new shortFormations
{
FkOperateur = formation.Key.FkOperateur,
FkPstStd = formation.Key.FkPstStd,
IdPoste = formation.FirstOrDefault()
.FkPstStdNavigation.FkPosteNavigation.IdPoste,
....
or order it and then select the correct record

Dynamic linq query with dynamic where conditions and from conditions

public GetApplicants(string Office,
int Id,
List<int> cfrparts,
List<int> expertiseAreaIds,
List<int> authIds,
List<int> specIds)
{
bool isAuthIdsNull = authIds == null;
authIds = authIds ?? new List<int>();
bool isSpecIdNull = specIds == null;
enter code here
var query =
from application in Apps
from cfr in application.cfr
from exp in cfr.Aoe
from auth in exp.Auth
from spec in exp.Special
where application.Design.Id == 14
where (iscfrpart || cfrPartIds.Contains(cfr.CfrP.Id))
where (isexp || expertiseAreaIds.Contains(exp.Aoe.Id))
where (isAuthIdsNull || authIds.Contains(auth.Auth.Id))
where (isSpecIdNull || specIds.Contains(spec.Special.Id))
where application.Office.Text.Contains(Office)
where application.D.Id == Id
select application.Id;
How can i make this query dynamic. If I have only Id and Office values It should still give me the resultset based on the avaliable values. Cureently its not giving me the result.
Instead of doing multiple calls to where, use &&
var query =
from Apps
where (iscfrpart || cfrPartIds.Contains(Apps.cfr.CfrP.Id))
&& (isexp || expertiseAreaIds.Contains(Apps.cfr.Aoe.Id))
&& (isAuthIdsNull || authIds.Contains(Apps.cfr.Aoe.Auth.Id))
&& (isSpecIdNull || specIds.Contains(Apps.cfr.Aoe.Special.Id))
&& Apps.Office.Text.Contains(Office)
&& Apps.D.Id == Id
select application.Id;
Additionally, this clause application.D.Id == 14 will cause 0 results when combined with this one: application.D.Id == Id if the passed in Id does not equal 14. You may want to delete that first clause.
Edit: updated your from clause, but I still don't think this will work because your table structure seems off.
Dynamic querying isn't required to solve this problem. You can write code that constructs the query.
Make a method that constructs your filter based on the information you have.
public Expression<Func<Application, bool>> GetFilterForCFR(List<int> cfrParts)
{
if (cfrParts == null || !cfrParts.Any())
{
return app => true;
}
else
{
return app => app.cfr.Any(cfr => cfrParts.Contains(cfr.cfrPId));
}
}
Then, you can construct the query using the expression.
var query = Apps;
var cfrFilter = GetFilterForCFR(cfrParts);
query = query.Where(cfrFilter);
//TODO apply the other filters
var finalquery = query.Select(app => app.Id);

Update row in database using LINQ - object copied

var queryResult = this.kindergardenDataContext.Groups.Where(g => g.group_id == groupToAdd.group_id && g.group_enabled==true);
if (queryResult != null && queryResult.Count() != 0)
{
Group groupToEdit = queryResult.First();
groupToEdit.group_name = groupToAdd.group_name;
groupToEdit.group_create_date = groupToAdd.group_create_date;
groupToEdit.Kindergarden = groupToAdd.Kindergarden;
groupToEdit.GroupGuardian = groupToAdd.GroupGuardian;
groupToEdit.Room = groupToAdd.Room;
}
this.kindergardenDataContext.SubmitChanges();
Hi. Im beginner in LINQ. Here is ok, but foreigns key kindergarden, groupguardian, room has been duplicated in database (added new rows in database in kindergarden, groupguardian, room table). How can I set good reference to update row in group table.
Unless you retrieved groupToAdd.Kindergarden, groupToAdd.GroupGuardian, andgroupToAdd.Roomfromthis.kindergardenDataContext` or attached them with the right IDs set, that is the expected behviour. It doesn't know that you mean the same object instances that already resides in the database.

Linq to Entities performance problem with many columns

I am having an issue with getting linq to entities to perform well. The query I have (not mine, maintaining someone's code :-)), has several includes that I've determined are all necessary for the WPF screen that consumes the results of this query.
Now, the SQL generated executes very fast and only returns one row of data. But it is returning 570 columns, and i think the performance hit is in the overhead of creating all the objects and all of those fields.
I've tried using lazy loading, but that doesn't seem to have any effect on performance.
I've tried removing any of the "include" statements that aren't necessary, but it appears that they all are needed.
here's the linq query:
var myQuery =
from appt in ctx.Appointments
.Include("ScheduleColumnProfile")
.Include("EncounterReason")
.Include("Visit")
.Include("Visit.Patient")
.Include("Visit.Patient.PatientInsurances")
.Include("Visit.Patient.PatientInsurances.InsuranceType")
.Include("Visit.Patient.PatientInsurances.InsuranceCarrier")
.Include("MasterLookup")
.Include("User1")
.Include("User2")
.Include("Site")
.Include("Visit.Patient_CoPay")
.Include("Visit.Patient_CoPay.User")
.Include("Visit.VisitInstructions.InstructionSheet")
where appt.VisitId == visitId
&& appt.MasterLookup.LookupDescription.ToUpper() != Rescheduled
&& appt.Site.PracticeID == practiceId
&& appt.MasterLookup.LookupDescription.ToUpper() != Cancelled
orderby appt.AppointmentId descending
select appt;
The SQL generate is 4000 lines long with 570 columns in the select statment and 3 or 4 Union ALLs, so I'm not going to paste it here unless someone REALLY wants to see it. Basically, i'm looking for a way to get rid of the unions if possible, and trim down the columns to only what's needed.
Help!
:-)
if anyone is keeping track, this is the solution that ended up working for me. Thanks to everyone who commented and made suggestions... it eventually lead me to what i have below.
ctx.ContextOptions.LazyLoadingEnabled = true;
var myQuery =
from appt in ctx.Appointments
where appt.VisitId == visitId
&& appt.MasterLookup.LookupDescription.ToUpper() != Rescheduled
&& appt.Site.PracticeID == practiceId
&& appt.MasterLookup.LookupDescription.ToUpper() != Cancelled
orderby appt.AppointmentId descending
select appt;
var myAppt = myQuery.FirstOrDefault();
ctx.LoadProperty(myAppt, a => a.EncounterReason);
ctx.LoadProperty(myAppt, a => a.ScheduleColumnProfile);
ctx.LoadProperty(myAppt, a => a.Visit);
ctx.LoadProperty(myAppt, a => a.MasterLookup);
ctx.LoadProperty(myAppt, a => a.User1);
ctx.LoadProperty(myAppt, a => a.User2);
ctx.LoadProperty(myAppt, a => a.PatientReferredProvider);
var myVisit = myAppt.Visit;
ctx.LoadProperty(myVisit, v => v.Patient);
ctx.LoadProperty(myVisit, v => v.Patient_CoPay);
ctx.LoadProperty(myVisit, v => v.VisitInstructions);
ctx.LoadProperty(myVisit, v => v.EligibilityChecks);
var pat = myVisit.Patient;
ctx.LoadProperty(pat, p => p.PatientInsurances);
//load child insurances
foreach (PatientInsurance patIns in myAppt.Visit.Patient.PatientInsurances)
{
ctx.LoadProperty(patIns, p => p.InsuranceType);
ctx.LoadProperty(patIns, p => p.InsuranceCarrier);
}
//load child instruction sheets
foreach (VisitInstruction vi in myAppt.Visit.VisitInstructions)
{
ctx.LoadProperty(vi, i => i.InstructionSheet);
}
//load child copays
foreach (Patient_CoPay coPay in myAppt.Visit.Patient_CoPay)
{
ctx.LoadProperty(coPay, c => c.User);
}
//load child eligibility checks
foreach (EligibilityCheck ec in myAppt.Visit.EligibilityChecks)
{
ctx.LoadProperty(ec, e => ec.MasterLookup);
ctx.LoadProperty(ec, e => ec.EligibilityResponse);
}
I would recommend creating a new Class that contains only the properties that you need to display. When you project to a new type you don't need to have Include statements, but you can still access the navigation properties of the entity.
var myQuery = from appt in ctx.Appointments
where appt.VisitId == visitId
&& appt.MasterLookup.LookupDescription.ToUpper() != Rescheduled
&& appt.Site.PracticeID == practiceId
&& appt.MasterLookup.LookupDescription.ToUpper() != Cancelled
orderby appt.AppointmentId descending
select new DisplayClass
{
Property1 = appt.Prop1,
Proeprty2 = appt.Visit.Prop1,
.
.
.
};

Linq To Nhibernate - Separated queries

I've got the following situation:
var totalRecords = (from entry in invalidAccEntryRepository
select entry).Where(entry =>
entry.CustomerAccountInfo.CustomerAccountName == CustomerAccountName &&
entry.CustomerAccountInfo.CustomerAccountId == CustomerAccountId).Count();
vs.
var totalRecords = (from entry in invalidAccEntryRepository
select entry);
if (CustomerAccountInfoFilterActive)
{
totalRecords.Where(entry =>
entry.CustomerAccountInfo.CustomerAccountName == CustomerAccountName &&
entry.CustomerAccountInfo.CustomerAccountId == CustomerAccountId);
}
totalRecordsCount = totalRecords.Count();
The first query works completely but the second query only executes the only
var totalRecords = (from entry in invalidAccEntryRepository
select entry);
and ignores the conditionally added where expression.
Anyone know what the problem could be? Do you need more info?
Thx in advance!
You aren't actually applying the where. In your if, use this instead:
totalRecords = totalRecords.Where(entry =>
entry.CustomerAccountInfo.CustomerAccountName == CustomerAccountName &&
entry.CustomerAccountInfo.CustomerAccountId == CustomerAccountId);

Resources