I am working on entity framework project, i have to apply Or condition in dbContext.Where
I have tried this but its giving me error "Operator || cannot be applied to operand of types lambda expressions"
return dataContext.Friends
.Where((r => r.ToUserId == touserid && r.FromUserId == fromuserid)
|| (r => r.ToUserId == fromuserid&& r.FromUserId == touserid ))
.ToList();
I also tried using && instead of || but its giving me same error for &&,how can i apply Or condition for this senario?
I have tried without brackets as well
You need to do it like this:
return dataContext.Friends.Where(r => (r.ToUserId == touserid && r.FromUserId == fromuserid) || (r.ToUserId == fromuserid && r.FromUserId == touserid))
.ToList();
The only difference is that I deleted the second r => and fixed the parenthesis.
Put it into one lambda that includes the || instead of ||ing two separate lambas:
return dataContext.Friends.Where(r => (r.ToUserId == touserid && r.FromUserId == fromuserid) || (r.ToUserId == fromuserid&& r.FromUserId == touserid)).ToList();
#Syed
|| (r => r.ToUserId == fromuserid&& r.FromUserId == touserid )).ToList();
Should be
|| (r => r.ToUserId == fromuserid && r.FromUserId == touserid )).ToList();
note the space between the "fromuserid&&".
Related
I have below LINQ query:
SailingMain_Details = SailingMain_Details.Where(f => f.Duration == durationCr_Filter
&& f.DeparturePortID == depPortCr_Filter
&& f.CruiseLine == cruLineCr_Filter
&& f.ShipName == cruShipCr_Filter
&& f.DestinationCr == destinationCr_Filter).ToList();
in above query sometime i get some parameters values like value=="any". in that situation i want to avoid checking only that parameter. Can anyone please guide me how to do that. Thanks.
The below might work if you want to skip the condition if the filter is "any"
SailingMain_Details =
SailingMain_Details.Where(f => (durationCr_Filter != "any" ? f.Duration == durationCr_Filter : true)
&& (depPortCr_Filter != "any" ? f.DeparturePortID == depPortCr_Filter : true)
&& (cruShipCr_Filter != "any" ? f.ShipName == cruShipCr_Filter : true)
&& (cruLineCr_Filter != "any" ? f.CruiseLine == cruLineCr_Filter : true)
&& (destinationCr_Filter != "any" ? f.DestinationCr == destinationCr_Filter : true)).ToList();
To achieve what you want let me show you by example with DeparturePortID. Let's say "any" valu eis -1:
SailingMain_Details = SailingMain_Details
.Where(f =>
f.Duration == durationCr_Filter
&& (depPortCr_Filter == -1 || f.DeparturePortID == depPortCr_Filter)
&& f.CruiseLine == cruLineCr_Filter
&& f.ShipName == cruShipCr_Filter
&& f.DestinationCr == destinationCr_Filter)
.ToList();
Here, if depPortCr_Filter is -1, then (depPortCr_Filter == -1 || f.DeparturePortID == depPortCr_Filter) evaluates to true, independently of f.DeparturePortID == depPortCr_Filter condition.
Apply every filter on separate. example
if(durationCr_Filter.toUpper() != "ANY")
SailingMain_Details = SailingMain_Details.Where(f => f.Duration == durationCr_Filter);
if(depPortCr_Filter.toUpper() != "ANY")
SailingMain_Details = SailingMain_Details.Where(f => f.DeparturePortID == depPortCr_Filter);
if(cruLineCr_Filter.toUpper() != "ANY")
SailingMain_Details = SailingMain_Details.Where(f => f.CruiseLine == cruLineCr_Filter);
if(cruShipCr_Filter.toUpper() != "ANY")
SailingMain_Details = SailingMain_Details.Where(f => f.ShipName == cruShipCr_Filter);
if(destinationCr_Filter.toUpper() != "ANY")
SailingMain_Details = SailingMain_Details.Where(f => f.DestinationCr == destinationCr_Filter);
I assume here some parameter means it can be for any of those 5 params so you can try something like
SailingMain_Details = SailingMain_Details.Where(f => (f.Duration == durationCr_Filter || durationCr_Filter == "any")
&& (f.DeparturePortID == depPortCr_Filter || depPortCr_Filter == "any") &&
(f.CruiseLine == cruLineCr_Filter || cruLineCr_Filter == "any") && (f.ShipName == cruShipCr_Filter || cruShipCr_Filter == "any") &&
(f.DestinationCr == destinationCr_Filter || destinationCr_Filter == "any") ).ToList();
You can do it like
if (SailingMain_Details.Any(x => x.value == "any"))
{
// avoid the check here
SailingMain_Details = SailingMain_Details.Where(f => f.Duration == durationCr_Filter && f.DeparturePortID == depPortCr_Filter && f.CruiseLine == cruLineCr_Filter && f.ShipName == cruShipCr_Filter && f.DestinationCr == destinationCr_Filter).ToList();
}
else
{
SailingMain_Details = SailingMain_Details.Where(f => f.Duration == durationCr_Filter && f.DeparturePortID == depPortCr_Filter && f.CruiseLine == cruLineCr_Filter && f.ShipName == cruShipCr_Filter && f.DestinationCr == destinationCr_Filter).ToList();
}
e.g avoid checking means basically it shall return true by default. for one item see below. other can follow the same
&& (depPortCr_Filter == 'any' || f.DeparturePortID == depPortCr_Filter).
I am a newbie with Linq and fluent validation and I want to know.. Why with the method 1 I get an error but with the method 2 it works without any issue?.
This way doesn't work!! throws a null reference exception.
RuleFor(x => x)
.Must(ledger => !_companyDbContext.GeneralLedger.Any(x =>
x.Deleted == false
&& !(x.Id == ledger.Id)
&& x.AccountNumber == ledger.AccountNumber
&& x.LedgerAccount == ledger.LedgerAccount
&& x.AccountType == ledger.AccountType
&& x.Description == ledger.Description
)).WithMessage(ValidatorResources.Unique_Message);
This way works even if all the properties of the object are null.
RuleFor(x => x)
.Must(testDuplicateRecords)
.WithMessage("duplicated record");
public bool testDuplicateRecords( GeneralLedger ledger)
{
Expression<Func<GeneralLedger, bool>> predicate = (x) => x.Deleted == false && !(x.Id == ledger.Id)
&& x.AccountNumber == ledger.AccountNumber
&& x.LedgerAccount == ledger.LedgerAccount
&& x.AccountType == ledger.AccountType
&& x.Description == ledger.Description;
return !_companyDbContext.GeneralLedger.Any(predicate.Compile());
}
I'm developing an ASP.NET MVC 4 Application and I'm trying to run this Lambda expression in Entity Framework 5.
var customer = db.GNL_Customer.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
.Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
.Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
.Where(d => d.GNL_CustomerLaptopProduct.Where(r => String.Compare(r.BrandName, brandID) == 0 || brandID == null));
I get this error :
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<ITKaranDomain.GNL_CustomerLaptopProduct>' to 'bool'
I know that the last where clause is wrong but I don't know how to correct it.
You might want another .Any instead of a .Where in your .Any clause at the end:
var customer = db.GNL_Customer.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
.Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
.Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
.Any(d => d.GNL_CustomerLaptopProduct.Any(r => String.Compare(r.BrandName, brandID) == 0 || brandID == null));
Use Where ( Any ) in last statement to select customers which have at least one product satisfying your conditions:
var customer = db.GNL_Customer
.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
.Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
.Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
.Where(d => brandID == null || d.GNL_CustomerLaptopProduct.Any(r => r.BrandName == brandID));
Probably something simple, but as I'm new to lambda expressions, the problem evades me:
m => m.contactID == contactID && m.primaryAddress == true && (m.addressTypeID == 2 || m.addressTypeID == 3)
I tried to use that lambda expression but I receive an invalid operator. Is there a way to simplify this so that it would work?
Edit:
The equivolent sql query would be:
SELECT *
FROM Contact
WHERE contactID = 3
AND primaryAddress = 1
AND (addressTypeID = 2 OR addressTypeID = 3)
I have a repository function defined like so:
public E Single(Expression<Func<E, bool>> where)
{
return objectSet.Single<E>(where);
}
I'm passing the lambda expression above into this function:
myRepository.Single(m => m.contactID == contactID && m.primaryAddress == true && (m.addressTypeID == 2 || m.addressTypeID == 3));
If you are receiving an InvalidOperationException, the most likely cause is that there is more than one record that matches your criteria.
Queryable.Single will raise InvalidOperationException if there is more than a single correct value. In this case, try using .First(m => ..) instead:
myRepository.First(m =>
m.contactID == contactID &&
m.primaryAddress == true &&
(m.addressTypeID == 2 || m.addressTypeID == 3)
);
This will return the first matching result, if there are more than one. If you need to handle no matches, look into FirstOrDefault (which will return null if there are no matches).
m.primaryAddress == true looks suspicious. is m.primaryAddress really a bool property?
m => (m.contactID == contactID && m.primaryAddress == true && (m.addressTypeID == 2 || m.addressTypeID == 3)) is merely a boolean expression.
You need to do something like
list.Remove(m => (m.contactID == contactID && m.primaryAddress == true && (m.addressTypeID == 2 || m.addressTypeID == 3))) etc
This says take each item in my list as m if this returns true remove m
Edit OP reposted while I was writing that answer
I would write this like this as to your syntax.
Func Filter<var, bool> = m => (m.contactID == contactID && m.primaryAddress == true && (m.addressTypeID == 2 || m.addressTypeID == 3))
then pass Filter into your myrepository.Single(Filter)
From your SQL query, should it be:
m => m.contactID == contactID && m.primaryAddress == 1 && (m.addressTypeID == 2 || m.addressTypeID == 3)
I want to get all records WHERE (s.override == 1 OR (s.override == 2 AND s.approved == 1))
How can I do that using the .Where x.subcontracts.Where(s ==> ??)
Use standard C# binary operators:
x.subcontracts
.Where(s => s.override == 1 || (s.override == 2 && s.approved == 1))
Here is the where clause you need:
x.subcontracts.Where(s => (s.override == 1) || (s.override == 2 && s.approved == 1))