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

问题描述 投票:1回答:2

我的表名是StcDocItems

id      partRef   DocTypeRef  itemRef
--------------------------------------
3850    366          12        NULL
3851    367          63        3850

我想将partRef更新为(在本例中为366)partRef的记录,其itemRef等于其Id,其DocTypeRef为63。

sql-server entity-framework
2个回答
2
投票

不完全确定你要做什么....假设你想要更新整个表,你可以尝试这样的事情:

  • 将整个表作为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
投票
Update StcDocItems set partRef =366 where itemRef=id and DocTypeRef =63
© www.soinside.com 2019 - 2024. All rights reserved.