1

//Below mentioned class is created to understand the problem, while this is created through Linq2Sql.

public class JobAds
{
 public int ID  { get; set; }
 public int EmployerRef { get; set;}
}

int? employerId = null;

var jobAdListing = JobAds.Where 
     ( n => (!employerId.HasValue || n.EmployerRef == employerId.Value )).ToList();

The Issue is I'm getting "Nullable object must have a value." at the above line. After doing some debugging, I feel n.EmployerRef == employerId.Value is making some trouble, but unable to find anything good.

2 Answers 2

1

Just write liks this, you don't have to worry about the null values (since NULL == NULL equals false)

int? employerId = null;
var jobAdListing = tblCompanies.Where 
     (n => (n.fkUserID_responsible == employerId)).ToList();

Or you can keep your code and just remove the ".value"

var jobAdListing = JobAds.Where 
     ( n => (!employerId.HasValue || n.EmployerRef == employerId)).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Good shot dude, take a virtual High Five from my side. Btw, I used the second option by removing the ".value".
1

in my local playground a simmilar case works with this easiest approach:

using (UnitOfWork.Begin("LinqToSql"))
{
    Guid? id1 = null;
    Guid? id2 = this.personRepository.GetAll().First().FavouriteProjectId;

    var all = this.personRepository.GetAll().Where(o => o.FavouriteProjectId == id1 || o.FavouriteProjectId == id2).ToArray();
}

for you, this should work too:

int? employerId = null;
int? employerType = null; /* OTHER Conditions */

var list = JobAds.Where(n => n.EmployerRef == employerId &&
                             n.EmployerTypeRef == employerType)).ToArray();

1 Comment

NET employerId is a local variable. But, I can't user IF condition over here, because I have around 6 local variables similar to employerId and you can imagine how many IF conditions I required. That's why, I'm using (!employerId.HasValue || n.EmployerRef == employerId.Value ) kinda code over here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.