我想插入一条记录,然后根据插入记录的scope_identity更新记录。 我这样做但是当我想更新我的记录时遇到错误。
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 :(得分:0)
正如它在错误上所说,你不能改变co_Workshop因为它的身份(自动增量值)。要自由编辑它,您需要编辑数据库并删除此设置。
可能发生的是id和co_Workshop都设置为identity。只需禁用co_Workshop的身份复选框。
答案 1 :(得分:0)
如果您已正确配置Linq-to-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
对象。
更新:将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();