2013-02-25 29 views
0

我在C#中这个数据表结果链接错误的DBNull

Date Employee Job1 Job2 Job3 
1/1/2012 a 1  1  1 
1/1/2012 b   2  
1/1/2012 c 2  1  4 
1/1/2012 d 4  2  1 
1/2/2012 a 3  2  5 
1/2/2012 b 2  2  2 
1/2/2012 c 3  3  3 
1/2/2012 d 1  1  1 
1/3/2012 a 5  5  5 
1/3/2012 b 2  2  6 
1/3/2012 c   1  1 
1/3/2012 d 2  3  4 
2/1/2012 a 2  2  2 
2/1/2012 b 5  5  2 
2/1/2012 c 2  2  2 
2/2/2012 a   3  
2/2/2012 b 2  3  3 
3/1/2012 a 4  4  2 

为了得到这样的结果:

岗位1:

Employee  January  February   March 
A    9    5     4 
B    6    7 
C    6    2 
D    7 

LINQ的代码是:

  var monthEmpGroups = tblEmpJobs.AsEnumerable() 
       .Select(r => new 
       { 
        Row = r, 
        Employee = r.Field<String>("Employee"), 
        Year = r.Field<DateTime>("Date").Year, 
        Month = r.Field<DateTime>("Date").Month 
       }) 
       .GroupBy(x => x.Employee); 

      DataTable tblMonthResultJob1 = new DataTable(); 
      tblMonthResultJob1.Columns.Add("Employee", typeof(string)); 
      var dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat; 

      foreach (var empGroup in monthEmpGroups) 
      { 
       string employee = empGroup.Key; 
       var newRow = tblMonthResultJob1.Rows.Add(); 
       newRow["Employee"] = employee; 
       var empMonthGroup = empGroup.GroupBy(mg => new { mg.Year, mg.Month }); 

       foreach (var empYearMonthGroup in empMonthGroup) 
       { 
        int year = empYearMonthGroup.Key.Year; 
        int month = empYearMonthGroup.Key.Month; 
        string colName = string.Format("{0} {1}", dtf.GetMonthName(month), year); 
        if (!tblMonthResultJob1.Columns.Contains(colName)) 
         tblMonthResultJob1.Columns.Add(colName, typeof(int)); 
        int empJob1Count = empYearMonthGroup.Sum(x => x.Row.Field<int>("Job1")); 
        newRow[colName] = empJob1Count; 
       } 
      } 

关于此线:

int empJob1Count = empYearMonthGroup.Sum(x => x.Row.Field<int>("Job1")); 
I am getting error: {System.InvalidCastException: Cannot cast DBNull.Value to type 'System.int'. Please use a nullable type. 

任何人都可以建议如何解决这个问题。

回答

1

从数据库返回的基础值为NULL,不能存储在int中。

改为使用可为空的int。

int empJob1Count = empYearMonthGroup.Sum(x => x.Row.Field<int?>("Job1") ?? 0); 

编辑

@Phil是相当正确的。请参阅使用空合并运算符。当基础值为空时,它将使用0来代替(它对Sum的影响不大)。

+0

此状态并没有工作,当我写这一行: INT empJob1Count = empYearMonthGroup.Sum(X => x.Row.Field ( “作业1”)); 我收到错误:不能隐式转换类型'int?'到'int'。显式转换存在(你是否缺少一个转换?) 所以我使用这一行: int empJob1Count = Convert.ToInt(empYearMonthGroup.Sum(x => x.Row.Field (“Job1”))); 仍然收到相同的错误。 – user1254053 2013-02-25 11:32:16

+3

它应该是x => x.Row.Field (“Job1”)?? 0 – Phil 2013-02-25 12:00:33

+0

谢谢@Phil。我确实怀疑Sum是否足够聪明,可以自动忽略空值。显然不是! :) – 2013-02-25 12:11:12

0

检查此

int empJob1Count = empYearMonthGroup.Where(x => x.Row["Job1"] != DBNull.value).Sum(x=>x.Row.Field<int>("Job1")); 
+0

没有阿比,这也是行不通的。错误无法将[]用[]指定为'AnonymousType#1'类型的表达式 - x [“Job1”] – user1254053 2013-02-25 11:40:25

+1

请检查代码现在...用x.Row [“Job1”]替换 – AbinZZ 2013-02-25 11:48:22