tags:

views:

128

answers:

4
+2  Q: 

C# Lambda Problem

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));
+1  A: 

m.primaryAddress == true looks suspicious. is m.primaryAddress really a bool property?

Wallstreet Programmer
its a bit operator in the database
Chris Klepeis
Meiscooldude
a bit operator? is it nullable?
Meiscooldude
Its not null in the database
Chris Klepeis
I'm pretty sure he would notice a compiler error guys.
Matthew Whited
A: 

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)

msarchet
+3  A: 

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).

Reed Copsey
Yup. Simple error on my end.
Chris Klepeis
A: 

From your SQL query, should it be:

m => m.contactID == contactID && m.primaryAddress == 1 && (m.addressTypeID == 2 || m.addressTypeID == 3)
Khnle