//创建下面提到的类是为了解问题,而这是通过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();
问题是我得到“Nullable对象必须有值”。在上面的那一行。做了一些调试后,我觉得n.EmployerRef == employerId.Value有些麻烦,但找不到任何好的东西。
答案 0 :(得分:1)
在我当地的游乐场,类似的案例采用这种最简单的方法:
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();
}
对你而言,这也应该有效:
int? employerId = null;
int? employerType = null; /* OTHER Conditions */
var list = JobAds.Where(n => n.EmployerRef == employerId &&
n.EmployerTypeRef == employerType)).ToArray();
答案 1 :(得分:1)
就这样写,你不必担心空值(因为NULL == NULL等于false)
int? employerId = null;
var jobAdListing = tblCompanies.Where
(n => (n.fkUserID_responsible == employerId)).ToList();
或者您可以保留代码并删除“.value”
var jobAdListing = JobAds.Where
( n => (!employerId.HasValue || n.EmployerRef == employerId)).ToList();