【发布时间】:2017-06-13 16:04:01
【问题描述】:
我正在编写一个 LINQpad 脚本来匿名存储在表的 XML 列中的 XML 对象的某些属性。我可以很好地访问数据,然后更改它,并通过 LINQpad Dump()s,它似乎已更新。但是,当我运行 SubmitChanges() 然后从 LINQ(或 SQL Server)运行另一个查询时,相关行尚未更新。
我试过用谷歌搜索这个问题,我发现一个常见问题与主键有关,我在 SQLStudio 中验证了正在使用的表确实有一个主键,所以我认为这不是问题。
此外,您可以在第一行中看到我已将 DataContext 上的 Log 设置为 Console.Out。启用此功能后,我会得到几行代码来验证我的第一个查询(选择)是否有效。但是,在运行我的 UpdateRecord 函数或运行 SubmitChanges 后,我在控制台中没有收到任何类型的 UPDATE 查询,可能是更新逻辑不正确?
更新:我在运行 SubmitChanges 之前添加了 GetChangeSet().Dump(),ChangeSet 中有 0 个更新和 0 个插入,确认我的 UpdateRecord 函数没有正确更新任何内容。
void Main() {
Log = Console.Out;
AnonymiseCommand("MyCommandName");
}
void AnonymiseCommand(string command) {
// Note we need to pluralise the table name for the LINQ query
// Table is actually called ChangeSet_Detail
var results = ChangeSet_Details
.Where(c => c.Command.ToString().Contains(command) )
.ToDictionary(row => (int) row.ChangeSetID,
row => row.Changes);
int commandCount = results.Count;
Print("Command count for " + command + " is " + commandCount + ".");
到目前为止一切正常,commandCount 正确返回 1,结果字典包含正确的值。接下来,我将遍历字典,并尝试更新 ID 与 dicts 键匹配的行,并将 XElement 映射到键。
foreach (KeyValuePair<int, XElement> entry in results) {
AnonymiseXml(entry.Value);
UpdateRecord(entry.Key, entry.Value);
}
}
// This function isn't so important, it anonymises the attributes and seems to work
void AnonymiseXml(XElement xml) {
// anonymise attributes
var attributes = xml.Attributes();
foreach(var attr in attributes) {
attr.Value = new String('?', attr.Value.Length);
}
// repeat across child nodes
var kiddies = xml.Elements();
foreach (var kid in kiddies) {
AnonymiseXml(kid);
}
}
void UpdateRecord(int rowID, XElement newXml) {
ChangeSet_Detail entry =
(from c in ChangeSet_Details
where c.ChangeSetID == rowID
select c).Single();
entry.Dump();
entry.ChangeSetID = rowID;
entry.Changes = newXml;
entry.Dump();
GetChangeSet().Dump();
try{
SubmitChanges();
} catch(Exception e) {
e.Dump();
}
}
UpdateRecord 函数是我尝试将更改提交到数据库的地方。我传入我们当前正在查看的行 ID 和新的 XML 元素。当我检索条目时,似乎我的更改仍然有效,在第一个 entry.Dump() 我可以看到属性是匿名的。无论如何我都会更改条目 XML 列(列名为 Changes),最后调用 SubmitChanges()。
如果我随后在 LINQpad 或 SQL Server 中查询表,我的更改还没有生效,属性也没有被匿名化。
【问题讨论】:
-
能否提供您的 SubmitChanges() 方法的代码实现?
-
SubmitChanges() 是一种 LINQ 方法
-
解决了,输入答案...
标签: c# mysql sql-server linq