I'm getting Nullable object must have a value after checking for null
on a regular object, after a null check. I've found various questions, mostly regarding linq-to-sql, having the same problem but always with nullable primitive types (as in bool?
or DateTime?
).
The line causing the exception in my case looks like this:
myDataContext.Orders.Where(y => customer.Address == null || (string.IsNullOrEmpty(customer.Address.Street) || y.Customers.Addresses.Street == customer.Address.Street)))
customer
class looks like this:
public class Customer
{
private Address address = null;
public Address Address{get{return address;} set{address=value;}}
}
address
property looks like this:
public class Address
{
private string street = null;
public string Street{get{return street ;} set{street =value;}}
}
If I replace above code line with this:
string custStreet = null;
if (customer.Address != null)
{
custStreet = customer.Address.Street;
}
myDataContext.Orders.Where(y =>(customer.Address == null || (string.IsNullOrEmpty(custStreet) || y.Customers.Addresses.Street == custStreet)))
it runs fine. I don't undestand the reason for that. I also don't want to define countless variables before executing the Lambda statement itself.
Please also note that above Lambda statement is part of a much bigger Lambda Where
clause that contains a few more of such statements. I know I could work with Expression Trees but having coded this far, I really don't want to switch now.
edit
as the question was answered, I'm going to tell you how I worked around it: I build myself a recursive property initializer. Everything that is not a string, a list/array or a primitive type is thrown against the Activator
class. I got the idea from here and made a few changes to it (basically, ignore everything that doesn't need to be initialized and instead of Activator.CreateInstance(Type.GetType(property.PropertyType.Name));
I used Activator.CreateInstance(property.PropertyType));
I'm not even sure if the version used in the original question would work or why anyone would want to use it.)