Linq To Entities中日期的差异

时间:2013-12-05 15:04:07

标签: c# linq

我正在努力争取不。通过减去2个日期的天数,但这两个试验都说 - ' DataSet不支持system.Nullable<>

public DataTable GetData()
{
    var qry = from a in MyDB.tblBranch.Where(a.EntryDate.HasValue && 
              a.exitdate.hasvalue)
              join e in MyDB.tblEmp on a.Eid equals e.Eid
              select new
              {
                 id = a.branchid,
                 name = e.empname,
                 days = System.Data.Objects
                        .EntityFunctions.DiffDays(a.ExitDate,a.EnterDate)

              };
     DataTable dt = qry.ToDataTable();
     return dt;
}

1 个答案:

答案 0 :(得分:0)

EntityFunctions.DiffDays()返回Nullable<int>,因此您必须处理空结果

例如

qry
    .Where(d => d.days.HasValue)
    .Select(d => d.Value)

修改

尝试那样的事情

var qry = MyDB.tblBranch
    .Where(a=>a.branchid==1)
    .Select(a => new
    {
        days = System.Data.Objects
            .EntityFunctions.DiffDays(a.ExitDate,a.EnterDate)
    })
    .Where(d => d.days.HasValue)
    .Select(d => d.Value);

DataTable dt = qry.ToDataTable();

如果你想保留空值,你可以像这样做

var qry = MyDB.tblBranch
    .Where(a=>a.branchid==1)
    .Select(a => new
    {
        days = System.Data.Objects
            .EntityFunctions
            .DiffDays(a.ExitDate,a.EnterDate)
    })
    .Select(b => b.HasValue ? (Object) b.Value :  DBNull.Value);