【问题标题】:Update specific cell in Dataset with LINQ使用 LINQ 更新数据集中的特定单元格
【发布时间】:2015-12-20 12:02:13
【问题描述】:

当我只知道用户帐号时,我想知道如何更新数据库(余额单元)中的特定井。

我不知道这将在数据库中的什么位置。我只知道帐号存在,因为我已经通过它登录了。

我需要为此使用 LINQ,并且我已尝试查询数据库以找到余额。虽然,我想将余额更新为特定值,而不是找到当前值。

在 SQL 中,我会这样做:

UPDATE UserData
SET Balance = some value in this case an int being passed in
WHERE AccNo = the accountNumber variable stored in a global class

但问题是,当客户端离线处理数据时,值存储在数据集中。一旦他注销,他的数据集就会在 SQL 数据库中更新。我打算通过从数据库中检索所有内容并执行更新/合并语句来做到这一点。

知道如何解决这个问题吗?

【问题讨论】:

  • DataSet 不包含单元格。它是数据表的集合
  • 我已经能够在数据集中检索到一个特定的余额,这就是我认为它有单元格的原因。

标签: c# sql-server linq datatable dataset


【解决方案1】:

Linq-To-DataSetLinq-To-Objects 的子集。您可以使用它查询 DataSet/DataTable,但不能使用它来更新行。

因此您可以使用 LINQ 搜索相关的 DataRows,然后使用循环来更新它们。

DataTable tblUserData = dataSet.Tables["UserData"];
var rowsWithAccount = from row in tblUserData.AsEnumerable()
                      where row.Field<string>("AccountNumber") == accountNumber // replace `<string>` with the right type
                      select row;
foreach(DataRow row in rowsWithAccount)
    row.SetField("Balance", newBalance);

值更新后,您可以使用SqlDataAdapter 更新数据库:

Updating Data Sources with DataAdapters

【讨论】:

  • 感谢您的回答!这是一个轻微的修改,所以我接受了它作为答案,尽管附上了我的修改。我将 where row.Field("AccountNumber") == accountNumber 更改为 Convert.ToString(row["AccountNo"]) == accountNumber 并且它可以在没有字符串错误的情况下工作。
  • @Paul:然后使用正确的数据类型(我已经用// replace &lt;string&gt; with the right type 评论过它)。我猜这是一个数字,可能是一个整数。然后使用where row.Field&lt;int&gt;("AccountNumber") == int.Parse(accountNumber)row.Field&lt;int&gt;("AccountNumber").ToString() == accountNumber
猜你喜欢
  • 1970-01-01
  • 2013-01-19
  • 2016-01-30
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
  • 2011-09-07
  • 1970-01-01
相关资源
最近更新 更多