代码之家  ›  专栏  ›  技术社区  ›  IsmailS

使用LINQ到SQL中的select查询中的值更新

  •  0
  • IsmailS  · 技术社区  · 14 年前
    Update TableToBeUpdated
    Set ColumnNameId = (Select MasterColumnId 
                        from MasterTable where Id = @Id)
    Where ForeingKeyId = @Id
       AND AnotherColumn = @AnotherColumn
    

    如何实现 在上面 有一个select语句和一个update语句吗?

    我现在想的是。

      //First Select statement
      var tableTBU = (from t in MsDataContext.TableToBeUpdated 
               where t.ForeingKeyId == <valueFromVariable>
               select t ).SingleOrDefault();
    
      //Second select statement
      var masterIdValue = (from m in MsDataContext.MasterTable 
                    where m.Id == <valueFromVariable>
                    select mod.MasterColumnId ).SingleOrDefault();
    
    
      tableTBU.ColumnNameId = masterIdValue ;
      tableTBU.SomeOtherColumn = "dkjsdlfs";
      //Some more things to be updated.
    
      //UpdateStatement
      MsDataContext.SubmitChanges();
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Neil T.    14 年前

    MasterTable TableToBeUpdated

    using (DataContext dc = new DataContext())
    {
        var objectToUpdate = dc.MasterTable.Single(a => a.Id == id).TableToBeUpdated;
    
        objectToUpdate.SomeOtherColumn = "dkjsdlfs";
        dc.SubmitChanges();
    }
    

    using (DataContext dc = new DataContext())
    {
        var objectToUpdate = dc.TableToBeUpdated
            .Single(b => b.ForeignKeyId.Contains(dc.MasterTable.Single(a => a.Id == id).Id)
                && b.AnotherColumn == anotherColumn);
    
        objectToUpdate.SomeOtherColumn = "dkjsdlfs";
        dc.SubmitChanges();
    }