Exception while trying to change value of fk
-
i have two tables Assest{assestid,name,parentid} account{accountid,name,assestid}//assestid is foreginkey to assest table the code Account account = DBContext.ctx.Accounts.Single( a => a.Account_ID == idacco); account.Account_Name = txt_nameAccount.Text.ToString(); account.Account_code = Convert.ToInt32(txt_CodeAccount.Text); account.AssestID = newid ; DBContext.ctx.SubmitChanges(); this exception Foreifn key reference already has valueexception was caught Operation is not valid due to the current state of the object. note newid is already founded in table assest
-
i have two tables Assest{assestid,name,parentid} account{accountid,name,assestid}//assestid is foreginkey to assest table the code Account account = DBContext.ctx.Accounts.Single( a => a.Account_ID == idacco); account.Account_Name = txt_nameAccount.Text.ToString(); account.Account_code = Convert.ToInt32(txt_CodeAccount.Text); account.AssestID = newid ; DBContext.ctx.SubmitChanges(); this exception Foreifn key reference already has valueexception was caught Operation is not valid due to the current state of the object. note newid is already founded in table assest
First off -- you will get a faster answer if you wrap your code with %lt;pre%gt; tags. So let's see if I isolated your code correctly:
Account account = DBContext.ctx.Accounts.Single( a => a.Account_ID == idacco);
account.Account_Name = txt_nameAccount.Text.ToString();
account.Account_code = Convert.ToInt32(txt_CodeAccount.Text);
account.AssestID = newid ;
DBContext.ctx.SubmitChanges();So now that I can SEE your code, the problem with your code is that you are totally violating database rules. You are taking an existing record and trying to change the key with this statement:
account.AssestID=newid;
Just what the heck are you trying to do??? Anyone that has passed Coding 101 should know you cannot change a database key value. Another issue is that you have your context off somewhere precreated which will quickly become a source of a memory leak or worse. If you are trying to put in a new record your code should be as follows:
using ( AccountsContext ctx = new AccountsContext()) { Account newRecord = new Account(); account.Account\_Name = blah blah bla ctx.Accounts.InsertOnSubmit(newRecord); ctx.SubmitChange(); }
If you are trying to actually change the record ID from 'a' to 'b' then you must do more complex logic than what you have there.
using ( AccountsContext ctx = new AccountsContext()) { Account oldRecord = ctx.Accounts.Single(a => a.Account\_ID == idacco); ctx.Accounts.DeleteOnSubmit(oldRecord); Account newRecord = new Account(); // make sure to use new instance ... set field values ctx.Accounts.InsertOnSubmit(newRecord); ctx.SubmitChanges(); }