LINQ SQL查询,SubmitChanges未向DB

时间:2017-06-13 16:04:02

标签: c# mysql sql-server linq

我正在编写一个LINQpad脚本来匿名化XML对象的某些属性,这些属性存储在表的XML列中。我可以正常访问数据,然后更改它,并通过LINQpad Dump(),它似乎更新。但是,当我运行SubmitChanges()然后从LINQ(或SQL Server)运行另一个查询时,相关行尚未更新。

我试过谷歌搜索这个问题,我发现一个常见的问题与主键有关,我在SQLStudio中验证过使用的表确实有一个主键,所以我不认为这是问题所在。

此外,您可以在第一行中看到我已将DataContext登录到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,结果字典包含正确的值。接下来,我将遍历字典,并尝试使用与dicts键匹配的ID更新行,并将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函数是我尝试将更改提交到DB的位置。我传入了我们当前正在查看的行ID和新的XML元素。当我检索条目时,似乎我的更改仍在第一个条目中生效。转储()我可以看到属性是匿名的。我无论如何都更改了条目XML列(列名为Changes),最后调用SubmitChanges()。

如果我然后在LINQpad或SQL Server中查询表,我的更改没有生效,属性也没有匿名化。

2 个答案:

答案 0 :(得分:0)

自己解决了。

所以我认为问题是,我正在改变XML值,即对象引用永远不会改变,XElement及其对象保持不变,但我改变了属性的字符串值,这可能意味着LINQ检测到没有变化。

当我告诉LINQ在运行SubmitChanges()之前刷新更改时,会记录更新并且我的更改会保留。

添加的内容很简单:

Refresh(RefreshMode.KeepCurrentValues, entry);

答案 1 :(得分:0)

      ComplaintComment tcc = new ComplaintComment();

            var Dat = DateTime.Now;

            tcc.comp_Id =1;
            tcc.cust_Id = 1;

            tcc.cc_Comments = txtComment.Text;

dbContext.ComplaintComments.InsertOnSubmit(tcc);