gpt4 book ai didi

c# - Linq to SQL - 无法更新

转载 作者:太空狗 更新时间:2023-10-29 20:06:18 25 4
gpt4 key购买 nike

我在更新 linq to sql 实体时遇到了一些麻烦。出于某种原因,我可以更新 item 实体中除 name 之外的每个字段。

下面是我写的两个简单的测试:

 [TestMethod]
public void TestUpdateName( ) {
using ( var context = new SimoneDataContext( ) ) {
Item item = context.Items.First( );

if ( item != null ) {
item.Name = "My New Name";
context.SubmitChanges( );
}
}
}

[TestMethod]
public void TestUpdateMPN( ) {
using ( var context = new SimoneDataContext( ) ) {
Item item = context.Items.First( );

if ( item != null ) {
item.MPN = "My New MPN";
context.SubmitChanges( );
}
}
}

不幸的是,TestUpdateName() 失败并出现以下错误:System.Data.SqlClient.SqlException:关键字“WHERE”附近的语法不正确..

这是输出的 SQL:

UPDATE [dbo].[Items] SET WHERE ([Id] = @p0) AND ([CategoryId] = @p1) AND ([MPN] = @p2) AND ([Height] = @p3) AND ([Width] = @p4) AND ([Weight] = @p5) AND ([Length] = @p6) AND ([AdministrativeCost] = @p7) -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1] -- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [1] -- @p2: Input VarChar (Size = 10; Prec = 0; Scale = 0) [My New MPN] -- @p3: Input Decimal (Size = 0; Prec = 5; Scale = 3) [30.000] -- @p4: Input Decimal (Size = 0; Prec = 5; Scale = 3) [10.000] -- @p5: Input Decimal (Size = 0; Prec = 5; Scale = 3) [40.000] -- @p6: Input Decimal (Size = 0; Prec = 5; Scale = 3) [30.000] -- @p7: Input Money (Size = 0; Prec = 19; Scale = 4) [350.0000] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.4926

如您所见,没有生成更新(SET 为空...)我不知道为什么会这样。

并且已经提前......是的,表 Item 有一个 PK (Id)。提前谢谢!

更新:该错误似乎是由覆盖 GetHashcode() 引起的。这是我当前的实现:


return string.Format( "{0}|{1}|{2}|{3}", Name, Id, UPC, AdministrativeCost).GetHashCode( );

最佳答案

听起来您的 DBML 可能不同步。您应该删除表并重新添加它们,然后再次尝试运行它。

只需手动删除您的Items 表并重新添加它。

编辑:根据您的编辑,您应该查看以下关于GetHashCode 的主题。

http://social.msdn.microsoft.com/forums/en-US/linqtosql/thread/6cc6c226-f718-4b22-baad-dba709afe74b/

.Net rules claim that GetHashCode() and Equals() must always be implemented in tandem. Two objects that are equal must have the same hash code.

Also, the combination of GetHashCode() + Equals() forms the entity's concept of identity. If you make it based on field values (other than PK) then the identity changes as you change the fields. This is bad if L2S must lookup other info in a dictionary based on the entity's identity, and especially if L2S needs to find an entity in its identity cache!

Advice: don't change the identity of an entity. L2S expects it to be based on the object's natural (address based) identity.

关于c# - Linq to SQL - 无法更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3017013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com