如何使用Entity Framework更新SQL Server中的表?

时间:2017-01-07 10:16:57

标签: sql-server entity-framework

我的表名是dcast(setDT(data)[rowb , on = .(R1=r1, R2 = r2, R3 = r3)], ...~C)

StcDocItems

我想更新id partRef DocTypeRef itemRef -------------------------------------- 3850 366 12 NULL 3851 367 63 3850 partRef的{​​{1}} partRef等于其itemRef及其{Id的记录{1}}是63。

2 个答案:

答案 0 :(得分:2)

不完全确定您要尝试做什么.... 假设您要更新整个表格,您可以尝试这样的事情:< / p>

  • 将整个表格作为List<StcDocItems>
  • 加载到内存中
  • 遍历每个项目并查看它是否有匹配的条目 - 如果是,请更新它

所以这就是执行此操作的代码:

public class StcDocItems
{
    public int Id { get; set; }
    public int PartRef { get; set; }
    public int DocRefType { get; set; }
    public int? ItemRef { get; set; }
}

using(YourDbContext ctx = new YourDbContext())
{
    // get all rows from table
    List<StcDocItems> allItems = ctx.StcDocItems.ToList();

    // iterate over items
    foreach(StcDocItems item in allItems)
    {
        // do we find a row which has "ItemRef = Id" and "DocTypeRef = 63" ?
        StcDocItems updateToItem = allItems.FirstOrDefault(i => i.ItemRef = item.Id && i.DocTypeRef = 63);

        // if we found an item
        if(updateToItem != null)
        {
            // set the partRef to new item's partRef
            item.PartRef = i.PartRef;
        }
    }

    // save any changes back to database table
    ctx.SaveChanges();
}  

答案 1 :(得分:1)

Update StcDocItems set partRef =366 where itemRef=id and DocTypeRef =63