使用Linq To SQL中的选择查询更新值

时间:2010-10-12 06:47:45

标签: linq-to-sql

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 个答案:

答案 0 :(得分:2)

如果允许LINQ引擎管理密钥,LINQ-to-SQL最有效(我假设MasterTableTableToBeUpdated之间的关系是一对一的):

using (DataContext dc = new DataContext())
{
    var objectToUpdate = dc.MasterTable.Single(a => a.Id == id).TableToBeUpdated;

    objectToUpdate.SomeOtherColumn = "dkjsdlfs";
    dc.SubmitChanges();
}

这也假设您已经使用关联或通过数据库中的外键关系手动通过设计器来关联这两个表。

<强>更新

由于您没有现有的外键关系,因此您需要手动关联表。基于上面的SQL语句:

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();
}