Linq to nHibernate - exclude elements without child elements - linq

var locations = (from location in session.Query<Location>()
where
(location.MB_ID == 0 || location.MB_ID == null) &&
(location.hide != "Y" || location.hide == null) &&
(location.locationNameRaw != "" && location.locationNameRaw != null) &&
((location.isIPCapableText != "" && location.isIPCapableText != null) || (
(location.ISDNNumber1 != null && location.ISDNNumber1 != "") ||
(location.ISDNNumber2 != null && location.ISDNNumber2 != "") ||
(location.ISDNNumber3 != null && location.ISDNNumber3 != "") ||
(location.ISDNNumber4 != null && location.ISDNNumber4 != "") ||
(location.ISDNNumber5 != null && location.ISDNNumber5 != "") ||
(location.ISDNNumber6 != null && location.ISDNNumber6 != "")
))
&& (location.privateRoom == "N" || location.privateRoom == "" || location.privateRoom != null)
&& (
from lll in session.Query<LocationLonLat>()
where
location.locationID == lll.locationId
select lll.locationId
).Any()
&& (location.LastUpdatedTime > lastUpdateTime)
&& location.LocationTimes.Count() > 0
/*&& (
from lt in session.Query<LocationTimes>()
where
location.locationID == lt.LID
select lt.LID
).Any()*/
select location
)
.ToList();
There is a relationship between Location (1) and LocationTimes (many), and I only want to return a dataset of locations that have at least one LocationTime record.
I tried a couple of things...
When I add the line:
&& location.LocationTimes.Count() > 0
or if I add the line:
&& (
from lt in session.Query<LocationTimes>()
where
location.locationID == lt.LID
select lt.LID
).Any()
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
I suspect that this may because of the size of the dataset or something...
Is there a better way of doing this? Like with a 'left outer join' or something?

I think a simple join should do it.
from locationTime in Query<LocationTime>()
join location in Query<Location>() on locationTime.Location.LocationId equals location.LocationId
join locationLat in Query<LocationLat>() on location.LocationLat.LocationLatId equals locationLat.LocationLatId
where ...
select location;

Related

Ignore part of the linq query if variable equals a specific value

var longlinq = viewModel.Where(x => (x.Systems.Storage == SelectOption || x.Systems.Laptop == SelectOption ||
x.Systems._2In1 == SelectOption ||
x.Systems.Convertible == SelectOption )
||
(x.Component.Components == SelectOptionComp ||
x.Component.Boards == SelectOptionComp)
||
( x.Service.Services == SelectOptionSer ||
x.Service.DevelopmentTools_andServices == SelectOptionSer )
||
(x.Software.Softwares == SelectOptionSoft ||
x.Software.Analytics == SelectOptionSoft)
||
(x.Application.Applications == SelectOptionApp ||
x.Application.PrintImaging_andOfficeAutomation ));
Let me explain my question with an example:
For instance SelectOptionComp equals "-", then I want to ignore the parts where I used
SelectOptionComp in longlinq or set SelectOptionComp to " " in the longlinq.
I don't want to use ifs because of large number of combinations.
How do I do that?
I have used ternary operator Use the ternary operator: (SelectOptionComp == "-" ? true : (x.Component.Components == SelectOptionComp || x.Component.Boards == SelectOptionComp))

Xcode slow compile time on equatable protocol

Xcode is taking too long to compile class's with equatable protocol, this is a little strange because in this particular case it's only comparing primitive types, this should be easy.
Took 608ms to type-check this:
public static func == (lhs: TheModel, rhs: TheModel) -> Bool {
return lhs.firstName == rhs.firstName &&
lhs.lastName == rhs.lastName &&
lhs.maritalStatus == rhs.maritalStatus &&
lhs.sex == rhs.sex &&
lhs.birthDate == rhs.birthDate &&
lhs.nationality == rhs.nationality &&
lhs.hasAnotherNationality == rhs.hasAnotherNationality &&
lhs.anotherNationality == rhs.anotherNationality &&
lhs.nif == rhs.nif &&
lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress &&
lhs.identificationCard == rhs.identificationCard &&
lhs.identificationCardNumber == rhs.identificationCardNumber &&
lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate &&
lhs.education == rhs.education &&
lhs.jobTitle == rhs.jobTitle &&
lhs.patronalEntity == rhs.patronalEntity &&
lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes &&
lhs.permanentAddressContainer == rhs.permanentAddressContainer &&
lhs.fiscalAddressContainer == rhs.fiscalAddressContainer &&
lhs.placeOfBirth == rhs.placeOfBirth &&
lhs.honorificTitle == rhs.honorificTitle &&
lhs.userType == rhs.userType &&
lhs.userTypeDescription == rhs.userTypeDescription &&
lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode &&
lhs.lastUpdate == rhs.lastUpdate
}
PS:I know this comparison it's a little overkill but it's only an example.
By the way, this was in MacbookPro with core i9, 64Gb of RAM and SSD.
Update - I made some changes and run some more tests:
Test 1
Added explicit type to a let and returned the let: Took ~450ms
public static func == (lhs: TheModel, rhs: TheModel) -> Bool {
let extractedExpr: Bool = lhs.firstName == rhs.firstName &&
lhs.lastName == rhs.lastName &&
lhs.maritalStatus == rhs.maritalStatus &&
lhs.sex == rhs.sex &&
lhs.birthDate == rhs.birthDate &&
lhs.nationality == rhs.nationality &&
lhs.hasAnotherNationality == rhs.hasAnotherNationality &&
lhs.anotherNationality == rhs.anotherNationality &&
lhs.nif == rhs.nif &&
lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress &&
lhs.identificationCard == rhs.identificationCard &&
lhs.identificationCardNumber == rhs.identificationCardNumber &&
lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate &&
lhs.education == rhs.education &&
lhs.jobTitle == rhs.jobTitle &&
lhs.patronalEntity == rhs.patronalEntity &&
lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes &&
lhs.permanentAddressContainer == rhs.permanentAddressContainer &&
lhs.fiscalAddressContainer == rhs.fiscalAddressContainer &&
lhs.placeOfBirth == rhs.placeOfBirth &&
lhs.honorificTitle == rhs.honorificTitle &&
lhs.userType == rhs.userType &&
lhs.userTypeDescription == rhs.userTypeDescription &&
lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode &&
lhs.lastUpdate == rhs.lastUpdate
return extractedExpr
}
Test 2
Added parenthesis to each case: Same result as Test 1!
let extractedExpr: Bool = (lhs.firstName == rhs.firstName) &&
(lhs.lastName == rhs.lastName) &&
(lhs.maritalStatus == rhs.maritalStatus) &&
(lhs.sex == rhs.sex) &&
(lhs.birthDate == rhs.birthDate) &&
(lhs.nationality == rhs.nationality) &&
(lhs.hasAnotherNationality == rhs.hasAnotherNationality) &&
(lhs.anotherNationality == rhs.anotherNationality) &&
(lhs.nif == rhs.nif) &&
(lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress) &&
(lhs.identificationCard == rhs.identificationCard) &&
(lhs.identificationCardNumber == rhs.identificationCardNumber) &&
(lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate) &&
(lhs.education == rhs.education) &&
(lhs.jobTitle == rhs.jobTitle) &&
(lhs.patronalEntity == rhs.patronalEntity) &&
(lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes) &&
(lhs.permanentAddressContainer == rhs.permanentAddressContainer) &&
(lhs.fiscalAddressContainer == rhs.fiscalAddressContainer) &&
(lhs.placeOfBirth == rhs.placeOfBirth) &&
(lhs.honorificTitle == rhs.honorificTitle) &&
(lhs.userType == rhs.userType) &&
(lhs.userTypeDescription == rhs.userTypeDescription) &&
(lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode) &&
(lhs.lastUpdate == rhs.lastUpdate)
return extractedExpr
Test 3
Added a bollean array as var with explicity type and append each condition: Took 171ms :)
public static func == (lhs: TheModel, rhs: TheModel) -> Bool {
var result: [Bool] = [Bool]()
result.append(lhs.firstName == rhs.firstName)
result.append(lhs.lastName == rhs.lastName)
result.append(lhs.maritalStatus == rhs.maritalStatus)
result.append(lhs.sex == rhs.sex)
result.append(lhs.birthDate == rhs.birthDate)
result.append(lhs.nationality == rhs.nationality)
result.append(lhs.hasAnotherNationality == rhs.hasAnotherNationality)
result.append(lhs.anotherNationality == rhs.anotherNationality)
result.append(lhs.nif == rhs.nif)
result.append(lhs.hasAnotherFiscalAddress == rhs.hasAnotherFiscalAddress)
result.append(lhs.identificationCard == rhs.identificationCard)
result.append(lhs.identificationCardNumber == rhs.identificationCardNumber)
result.append(lhs.identificationCardExpirationDate == rhs.identificationCardExpirationDate)
result.append(lhs.education == rhs.education)
result.append(lhs.jobTitle == rhs.jobTitle)
result.append(lhs.patronalEntity == rhs.patronalEntity)
result.append(lhs.hasLivesOfIncomes == rhs.hasLivesOfIncomes)
result.append(lhs.permanentAddressContainer == rhs.permanentAddressContainer)
result.append(lhs.fiscalAddressContainer == rhs.fiscalAddressContainer)
result.append(lhs.placeOfBirth == rhs.placeOfBirth)
result.append(lhs.honorificTitle == rhs.honorificTitle)
result.append(lhs.userType == rhs.userType)
result.append(lhs.userTypeDescription == rhs.userTypeDescription)
result.append(lhs.lastVisitedCountryCode == rhs.lastVisitedCountryCode)
result.append(lhs.lastUpdate == rhs.lastUpdate)
return !result.contains(false)
}

LINQ to Entities grouped logical operations in Where

I'm trying to execute the following linq query and it seems to be ignoring order of operations. (Parentheses first)
var result = _repo.Transactions.Where(t =>
t.DateEntered > EntityFunctions.AddDays(DateTime.Now, -7)
&& ( t.TranDesc != "BALANCE FORWARD" && t.Withdrawl == 0 && t.Deposit == 0 ) );
Here's the where clause that generates:
WHERE ([Extent1].[dateentered] > (DATEADD (day, -7, SysDateTime())))
AND (N'BALANCE FORWARD' <> [Extent1].[TranDesc])
AND (cast(0 as decimal(18)) = [Extent1].[Withdrawl])
AND (cast(0 as decimal(18)) = [Extent1].[Deposit])
Any ideas what I'm doing wrong?
EDIT:
This is actually what I wanted and it solved my problem. Just didn't think it all the way though. Thanks.
var result = _repo.Transactions.Where(t =>
t.dateentered > EntityFunctions.AddDays(DateTime.Now, -7)
&& ((t.TranDesc == "BALANCE FORWARD" && (t.Withdrawl != 0 || t.Deposit != 0))
|| (t.TranDesc != "BALANCE FORWARD")));
There is no difference between a && (b && c && d) and a && b && c && d, and that's why parentheses within generated SQL are not exactly the same as in your LINQ query. But at the end there is no difference between these queries.

How to simplify a simple loop in Javascript?

I am now trying it out for a while and get it perfect. I am trying to simplify this for loop I created and make it actually work, without any arrays and only the most basic of basic JavaScript.
for (var x=0;x<=1;x++) {
if (secondInput == luckyNumber || secondInput == luckyNumber2 || secondInput == luckyNumber3) {
if (thirdInput == luckyNumber || thirdInput == luckyNumber2 || thirdInput == luckyNumber3) {
if (firstInput == luckyNumber || firstInput == luckyNumber2 || firstInput == luckyNumber3) {
while (firstInput !== secondInput){
while(firstInput !== thirdInput){while(secondInput !== thirdInput) {
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1,000!');
}
}
}
}
}
}
Does this code make sense or am I doing something wrong? I've got the feeling that I can even leave the loop out, but it is the only way how I think it is correct.
Write a function that takes the input, compares it to the lucky numbers and returns a boolean with the result.
Call that function in your if clauses.
I don't quite understand what you are trying to do with the while loops.
You could try using this idea to help:
[1, 3, 2].sort()
(store your questions and answers in arrays, and sort both then compare. Of course, checking javascript arrays for equality is a fun new project :) )
Here you go. You said you wanted it simplified.
for (var x = 0; 1 >= x; x++) {
if (!(secondInput != luckyNumber && secondInput != luckyNumber2 && secondInput != luckyNumber3 || thirdInput != luckyNumber && thirdInput != luckyNumber2 && thirdInput != luckyNumber3 || firstInput != luckyNumber && firstInput != luckyNumber2 && firstInput != luckyNumber3)) {
while (firstInput !== secondInput) {
while (firstInput !== thirdInput) {
while (secondInput !== thirdInput) {
alert("Congratulations! You got all 3 numbers correct. You\'ve won £1,000!");
}
}
}
}
}

help with linq query

i am trying to get some data, but i dont know how can i do a if in linq, this is how i am trying to do
from so in db.Operations
where ((opType!= "0" ? so.Operation == int.Parse(opType) : false)
&& (idState!=0 ? so.State == idState : false)
&& (start != null ? so.StartDate == start : false)
&& (end !=null ? so.EndDate == end : false))
select so
the optype is a Int,
the idState is a Int,
end is a datetime,
start is a datime
what i am trying to do is, if those aren't null they add to the query function, so i can get all data together
for example: in c# code
if((opType!= "0")
where (so.Operation == int.Parse(opType)
if(idState!=0)
where (so.Operation == int.Parse(opType) && so.State == idState
.......
so if that isn't null, that sentence in that sql query (the TRUE part, i dont want to use the false part), add it to the where, so i can search all parameters that aren't null or 0
Since you're &&'ing them, looks like you want : true instead of : false.
Well not sure what you want exactly but here is a try:
var query = db.Operations.AsQueryable();
if (opType != null && opType != "0")
query = query.Where(x => x.Operation == int.Parse(opType);
if (idState != 0)
query = query.Where(x => x.State == idState);
if (start != null) // assuming that start is of type DateTime? otherwise use DateTime.MinValue
query = query.Where(x => x.StartDate.Date == start); // maybe >= is more appropriate
if (end != null) // also DateTime? assumed
query = query.Where(x => x.EndDate.Date == end); // maybe <= is more appropriate
var result = query.ToList(); // e.g. could also do an foreach, depending what you want to do
The trick in this approach is to build up the query successively. The query will not be enumerated until .ToList() or foreach is used to enumerate the list.
Actually this should yield the same:
from so in db.Operations
where ((opType != null && opType!= "0" ? so.Operation == int.Parse(opType) : true)
&& (idState!=0 ? so.State == idState : true)
&& (start != null ? so.StartDate.Date == start : true)
&& (end !=null ? so.EndDate.Date == end : true))
select so
opType!= "0" ? so.Operation == int.Parse(opType) : false
you should not use so.operation == int.parse.... instead use so.operation = int.Parse(opType)
You can use conditional parameters.
Change:
where ((opType!= "0" ? so.Operation == int.Parse(opType) : false)
To:
where ((opType!= "0" ? so.Operation == int.Parse(opType) : so.Operation == Operation)
and so on...

Resources