使用null对象在c#中连接数据表

时间:2012-08-28 10:48:23

标签: c# sql linq

当我在记录中有空值时,我在连接表时遇到问题。

有2个dataTables:

  1. 工人:(workerID,workerName,workerAdress)
  2. 事务:(transactionID,transactioinValue,worker1,worker2),其中worker 2是可选的,因此它可以包含空值。
  3. 所以我开始这样的代码:

    var record = from transaction in dtTransactions.AsEnumerable()
        join worker1 in dtWorkers.AsEnumerable() on (int)transactions["worker1"] equals (int)worker1["workerID"]
        join worker2 in dtWorkers.AsEnumerable() on (int)transactions["worker2"] equals (int)worker2["workerID"]
        select new
        {
         ID = (int)transactions["transactionID"],
         Name1= worker1["workerName"],
         Name2= worker2["workerName"]
        };
    

    因此,如果worker2不为null,那么一切正常,但是当我有一个空值时,它无法连接。有人可以帮我解决这个问题,如果在dataTable中为null,我想有一个没有worker2名称的结果记录。

    有可能吗?

2 个答案:

答案 0 :(得分:1)

你需要做这样的左连接;

var record = from transaction in dtTransactions.AsEnumerable()
                     join worker1 in dtWorkers.AsEnumerable() on (int)transactions["worker1"] equals (int)worker1["workerID"]
                     join worker2 in dtWorkers.AsEnumerable() on (int)transactions["worker2"] equals (int)worker2["workerID"] into w2
                     from wrk in w2.DefaultIfEmpty()
                     select new
                     {
                         ID = (int)transactions["transactionID"],
                         Name1= worker1["workerName"],
                         Name2= wrk["workerName"]
                     };

其次,你有没有理由不指定像这样的对象属性;

                var record = from transaction in dtTransactions.AsEnumerable()
                 join worker1 in dtWorkers.AsEnumerable() on (int)transactions.worker1 equals (int)worker1.workerID
                 join worker2 in dtWorkers.AsEnumerable() on (int)transactions.worker2 equals (int)worker2.workerID into w2
                 from wrk in w2.DefaultIfEmpty()
                 select new
                 {
                     ID = (int)transactions.transactionID,
                     Name1= worker1.workerName,
                     Name2= wrk != null ? wrk.workerName : ""
                 };

请注意删除方括号

答案 1 :(得分:0)

from x in left
where x.Id != null
join y in right on x.Id equals y.Id into rightMatches
from y2 in rightMatches.DefaultIfEmpty() 
select new {x, y2};