I want to insert a record and then update the record according to s开发者_如何学Ccope_identity of inserted record. I'm doing this but when I want to update my record encounter an error.
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();
and this is the error:
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.
If you have properly configured your Linq-to-SQL model to reflect the IDENTITY
column in your table, you should have the new value available right after .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!!
You don't need to do anything like reading out that new value from SQL Server or anything - Linq-to-SQL should automagically update your Workshop
object with the proper value.
Update: to update your co_workshop
value to the value given by the IDENTITY ID
, do this (just set the value of co_workshop
and save again - that's really all there is):
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();
As it said on the error, you can't change co_Workshop because its identity (auto increment value). To freely edit it, you need to edit the database and remove this setting.
What probably is happening is that both id and co_Workshop are set as identity. Just disable the identity checkbox from co_Workshop.
精彩评论