Linq使用Mulitple表更新查询

时间:2015-09-15 05:20:29

标签: c# sql entity-framework linq

我需要将以下查询转换为Linq: -

UPDATE INOUT
SET TIME_FLD1 = A.SCODE,
    TIME_FLD2 = B.STATUS
FROM SHIFTSCHEDULE A,
     SHIFT B,
     INOUT C
WHERE A.COMPANY = B.COMPANY
  AND A.SCODE = B.SCODE
  AND A.CODE = C.CODE
  AND A.SHIFT_DATE = C.DATE1

通常我会像这样更新: -

    var data = ctx.INOUT.Where(m=>m.COMPANY == COMPANY).Select(m=>m).FirstOrDefault();
    ctx.INOUT.Attach(rec);    
    ctx.Entry(data).State = EntityState.Modified;
    ctx.SaveChanges();

有人可以解释一下Sql查询的确切功能吗?如何在Linq中完成?

2 个答案:

答案 0 :(得分:0)

我想这就是你要找的东西:

        //Select your data
        var data = from A in contextDB.SHIFTSCHEDULE
                    from B in contextDB.SHIFT
                    from C in contextDB.INOUT
                    where   A.COMPANY == B.COMPANY
                            && A.SCODE == B.SCODE 
                            && A.CODE == C.CODE 
                            && A.SHIFT_DATE == C.DATE1
                    select new { A, B, C};

        //interate througt collection and update
        foreach (var row in data)
        {
            row.C.TIME_FLD1 = row.A.SCODE;
            row.C.TIME_FLD2= row.B.STATUS;
        }
        //save changes
        contextDB.SaveChanges();

Linq to SQL无法同时更新多条记录。这很可怜,但这是真的,所以你应该得到你的收藏,然后逐个更新实体。

答案 1 :(得分:-1)

SQL查询正在从多个表进行更新,其LINQ版本应如下所示:

var data = (from A in contextDB.SHIFTSCHEDULE
        from B in contextDB.SHIFT
         from C in contextDB.INOUT
        where A.COMPANY==B.COMPANY
        && A.SCODE==B.SCODE && A.CODE==C.CODE && A.SHIFT_DATE==C.DATE1
        select new {A,B,C}).FirstOrDefault();
if(data != null)
{
  data.TIME_FLD1= data.SCODE,
  data.TIME_FLD2= data.STATUS
 contextDB.SubmitChanges();
 }