2011-05-08 170 views
0

我想插入一條記錄,然後根據插入記錄的scope_identity更新記錄。 我正在這樣做,但是當我想更新我的記錄時遇到錯誤。根據LINQ中插入記錄的ID更新記錄到SQL

WorkshopDataContext Dac = new WorkshopDataContext(); 
Dac.Connection.ConnectionString = "Data Source=dpsxxx-xxx;Initial Catalog=kar;User ID=sa;Password=xxxx"; 
Tbl_workshop Workshop = new Tbl_workshop(); 
Workshop.StateCode = Bodu.BduStateCode; 
Workshop.CityCode = Bodu.BduCityCode; 
Workshop.Co_workshop=12222; 
Dac.Tbl_workshop.InsertOnSubmit(Workshop); 
Dac.SubmitChanges(); 
Int64 Scope = Workshop.id; 
var query = from record in Dac.Tbl_workshop where record.id == Scope select record; 
     query.First().co_Workshop = Scope; 
Dac.SubmitChanges(); 

,這是錯誤:

Value of member 'co_Workshop' of an object of type 'Tbl_Workshop' changed. 
A member defining the identity of the object cannot be changed. 
Consider adding a new object with new identity and deleting the existing one instead. 

回答

0

由於它的錯誤說,你不能改變co_Workshop因爲其身份(自動增加值)。要自由編輯它,您需要編輯數據庫並刪除此設置。

可能發生的情況是id和co_Workshop都被設置爲身份。只需從co_Workshop中禁用身份複選框即可。

+0

否'Co_Workshop'不是身份,它只是主鍵 – 2011-05-08 15:00:00

+0

然後檢查Linq DBML,也許它不同步 – ariel 2011-05-08 15:01:35

+0

我檢查了它,沒關係。我是否正在更新?我在'co_kargah'中插入了12222的值,並且在插入記錄後,我想用同一個表中的插入記錄的'id'更新它 – 2011-05-08 15:05:40

0

如果你已經正確配置您的LINQ到SQL模型來反映你的表格中IDENTITY列,你應該有新的價值可右後.SubmitChanges()

Tbl_workshop Workshop = new Tbl_workshop(); 
Workshop.StateCode = Bodu.BduStateCode; 
Workshop.CityCode = Bodu.BduCityCode; 
Workshop.Co_workshop=12222; 

Dac.Tbl_workshop.InsertOnSubmit(Workshop); 
Dac.SubmitChanges(); 

Int64 workshopID = Workshop.Id; // you should get new ID value here - automatically!! 

你不需要做例如從SQL Server讀取新值或任何東西 - Linq-to-SQL應自動更新您的Workshop對象的正確值。

enter image description here

更新:更新您的co_workshop值由IDENTITY ID給出的值,這樣做(只設置的co_workshop值,並再次保存 - 這就是所有要做的):

Dac.Tbl_workshop.InsertOnSubmit(Workshop); 
Dac.SubmitChanges(); 

Int64 workshopID = Workshop.Id; // you should get new ID value here - automatically!! 

Workshop.Co_workshop = workshopID; 
Dac.SubmitChanges(); 
+0

獲取插入記錄的ID後,我想用'id'字段更新'Co_Workshop'。我該怎麼辦? 'Co_workshop'不是身份它只是主鍵 – 2011-05-08 14:58:13

+0

我試過你的代碼。但我再次得到相同的錯誤 – 2011-05-08 15:09:23

+0

@Raymond Morphy:你最近是否改變了你的數據庫模式,並且在那之後可能沒有更新你的Linq-to-SQL模型? – 2011-05-08 16:53:36