//下面提到的类是为了理解问题而创建的,而这是通过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();
问题是我在上面的行中得到"可为空的对象必须有一个值"。经过一些调试,我觉得n.EmployerRef == employerId.Value正在制造一些麻烦,但找不到任何好的东西。
只要写喜欢这个,你就不必担心空值(因为 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();
在我当地的操场上,一个类似的案例可以使用以下最简单的方法:
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();