Facing problem in Linq to sql
//Below mentioned class is created to understand the proble开发者_开发百科m, 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.
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();
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();
精彩评论