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)
Related
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 currently running the following query:
var results = from c in _context.Cs
join a in _context.Ca on c.Id equals a.CId
where c.Status == "A"
where c.CtId == ctId
where c.FY == fYear
where (a.PMId == lUserId || a.TLId == lInUserId)
select new { c.Id, c.T, c.C, c.S } into x
group x by new {x.Id, x.T, x.C, x.S} into g
orderby g.Key.T, g.Key.C, g.Key.S
select new { Id = g.Key.Id, T = g.Key.T, C = g.Key.C, S = g.Key.S}
Now I need to make the where (a.PMId == lUserId || a.TLId == lInUserId) line conditional on if lUserId != 0 (use it if not 0, ignore it if 0).
Normally, I would declare the variable results then set it in an if statement, but I have no idea how to define this data structure. It shows as being defined as:
IQueryble<'a>
'a is new { int Id, string T, string C, string S}
Whats the best way to accomplish this?
You can use || operator in the query so if first condition is true, the second will not be evaluated and if first is false that is not equal to 0 second will be evaluated:
where lUserId ==0 || (a.PMId == lUserId || a.TLId == lInUserId)
What I understand is:
use the condition a.PMId == lUserId || a.TLId == lInUserId if and only if UserId != 0
Ignore that condition if lUserId ==0
If I understand the requirement correctly, then && will be the operator that you have to use here. since it will skip checking the second condition if the first condition is false(that is UserId == 0).
I think you are looking for this:
where (UserId != 0 && a.PMId == lUserId || a.TLId == lInUserId)
I have a query
return uow.CustomerRepo
.Get()
.Where
(
c=>
c.Firstname.StartsWith(customerSearch.Initial) &&
c.Surname == customerSearch.Surname &&
c.Email == customerSearch.Email &&
c.Postcode == customerSearch.PostCode
)
Is there a way to skip parts of the query if something in customerSearch is empty?
so I want to skip the part
c.Surname == customerSearch.Surname
if
customerSearch.Surname
Is empty
You can do it with a condition that checks the customerSearch part explicitly:
.Where
(
c=>
(customerSearch.Initial == null || c.Firstname.StartsWith(customerSearch.Initial)) &&
(customerSearch.Surname == null || c.Surname == customerSearch.Surname) &&
(customerSearch.Email == null || c.Email == customerSearch.Email) &&
(customerSearch.PostCode == null || c.Postcode == customerSearch.PostCode)
)
If you need to check for empty strings rather than null, change the condition accordingly.
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&&".
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))