关键字' WHERE'附近的语法不正确使用SQLMetal生成的类更新表时

时间:2016-08-09 15:50:58

标签: c# sql linq-to-sql sqlmetal

我在SQL Server中有一个非常基本的表(双键,没有外键)。我使用SQLMetal生成了映射代码。我还扩展了自动生成的分部类,因此我可以实现IEquatable。问题是,一旦我实现IEquatable,我就失去了使用我的SQLMetal生成的类更新记录的能力。提交更改时,我会收到以下异常:

  

关键字' WHERE'

附近的语法不正确

下面的示例代码说明了问题。它运行正常,直到实现IEquatable:

var connection = "Your connection string";
var dbInsert = new DBTest(connection);
var recordToInsert = new TestTable()
{
    PrimaryKey1 = 123,
    PrimaryKey2 = "Red",
    TheValue = Guid.NewGuid().ToString(),
};
dbInsert.TestTable.InsertOnSubmit(recordToInsert);
dbInsert.SubmitChanges();

var dbEdit = new DBTest(connection);
dbEdit.Log = Console.Out;
var ti1 = dbEdit.TestTable.Single(x => x.PrimaryKey1 == 123 && x.PrimaryKey2 == "Red");
ti1.TheValue = Guid.NewGuid().ToString();
dbEdit.SubmitChanges();

这是我对IEquatable的实现(由ReSharper自动生成):

public partial class TestTable : IEquatable<TestTable>
{
    public bool Equals(TestTable other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return _PrimaryKey1 == other._PrimaryKey1 && string.Equals(_PrimaryKey2, other._PrimaryKey2) && string.Equals(_TheValue, other._TheValue);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((TestTable)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = _PrimaryKey1;
            hashCode = (hashCode * 397) ^ (_PrimaryKey2 != null ? _PrimaryKey2.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (_TheValue != null ? _TheValue.GetHashCode() : 0);
            return hashCode;
        }
    }
}

查看在输出窗口中打印出的查询。实现IEquatable时,SET子句为空(并导致抛出异常):

  

更新[dbo]。[TestTable]
  SET
  WHERE([PrimaryKey1] = @ p0)AND([PrimaryKey2] = @ p1)AND([TheValue] = @ p2)
   - @ p0:输入Int(大小= -1; Prec = 0; Scale = 0)[123]
   - @ p1:输入NVarChar(大小= 4000; Prec = 0; Scale = 0)[红色]
   - @ p2:输入NVarChar(大小= 4000; Prec = 0; Scale = 0)[8dedfdca-84e9-4b7a-9268-4bbdde2e9ad2]

这是没有实现IEquatable的相同输出:

  

更新[dbo]。[TestTable]
  SET [TheValue] = @ p3
  WHERE([PrimaryKey1] = @ p0)AND([PrimaryKey2] = @ p1)AND([TheValue] = @ p2)
   - @ p0:输入Int(大小= -1; Prec = 0; Scale = 0)[123]
   - @ p1:输入NVarChar(大小= 4000; Prec = 0; Scale = 0)[红色]
   - @ p2:输入NVarChar(大小= 4000; Prec = 0; Scale = 0)[8f6e72ee-f89e-40f3-830f-18e8b4b40f9e]
   - @ p3:输入NVarChar(大小= 4000; Prec = 0; Scale = 0)[1ecaff9d-d460-4f3e-b35d-138ddeb2fb63]

预计会出现这种情况吗?有没有办法解决它?

1 个答案:

答案 0 :(得分:1)

事实证明,覆盖GetHashCode()方法会混淆DataContext跟踪更改的能力。删除GetHashCode覆盖解决了该问题。