Linq to SQL replace related object

I have an object Clientand an object PostCodein the Linq to SQL model. The table Clientsin the database contains a column client_postcodethat is the FK column for the zip code column in the table PostCode, which is the primary key of the varchar column for the PostCode table.

When updating the client in my code, I do this

        // postcode
        updating.PostCode = (from p in ctx.PostCodes
                             where p.postalcode.Equals(client.PostCode.postalcode)
                             select p).First();

where the Clientobject is provided from an ASP.NET MVC view form. This code seems to be great for an object related to PostCode. But when I call the SubmitChanges () function, I get the following exception:

Changed the value of the "zip code" of a member of an object of type "PostCode". The member defining the identity of an object cannot be changed. Consider adding a new object with a new identifier and deleting an existing one.

Therefore, I cannot change the associated object. How is this done in Linq to Sql?

UPDATE:

After further analysis and troubleshooting, it turned out that the problem was related to calling ASP.NET MVC UpdateModel (). If I call UpdateModel () to update an existing object with edited data, something is wrong with the FK assignment for PostCode. If I do not allow UpdateModel and do it manually, it will work. Any ideas what goes wrong in UpdateModel () that it cannot properly set up the relation to foreign key objects?

. . L2S UpdateModel() ( FK) ASP.NET MVC ?

+3
3

, PostCode.postalcode http post request.

, , UpdateModel .PostCode.postalcode , .

.

+2

updating.client_postcode = client.client_postcode; , ?

Client.PostCode client_postocde.

0

, , Postcode.

.

Updatemodel() Formcollection

Formcollection? keys?

.

1:

, , Formcollection, Updatemodel() . do SubmitChanges()

2:

, ( ) SubmitChanges()

, , . update.client_postcode, ?

? .

0

Source: https://habr.com/ru/post/1762502/


All Articles