Cannot modify a primary key member

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
alekas
Posts: 4
Joined: Thu 14 Feb 2013 19:34

Cannot modify a primary key member

Post by alekas » Sun 17 Mar 2013 02:34

I am getting this error when I try to update a field in table that is a part of a composite primary key:

Cannot modify a primary key member (Devart.Data.Linq.Mapping.MetaDataMember) of an entity (xxx).

The field is not read only and the record is not referencing by a foreign key from another table.

Am I doing something wrong?

Thanks,
Alex

MariiaI
Devart Team
Posts: 1472
Joined: Mon 13 Feb 2012 08:17

Re: Cannot modify a primary key member

Post by MariiaI » Mon 18 Mar 2013 13:40

LinqConnect identifies and tracks entity objects by their primary key. For this reason, it is not allowed to directly change the primary key of entities.
The entities that were already retrieved from the database are cached in DataContext; the cache key is the primary key of the entity class. If it were possible to modify the keys, trying to work with these cached entities would possibly cause errors (for example, SQL commands generated to change them will use old key values and thus will fail).

The possible ways to change the primary key of a row are:
- to delete the entity object and then insert its copy with modified key field(s) (as it doesn't have dependent entities);
- to change the key via an explicit SQL command (if you change the key with an explicit SQL, you should create a new DataContext instance and dispose the old one).

Please tell us if this helps.

alekas
Posts: 4
Joined: Thu 14 Feb 2013 19:34

Re: Cannot modify a primary key member

Post by alekas » Tue 19 Mar 2013 01:46

Thank you for a reply.

What if the table does not have a primary key defined? Can I use such a table in LinqConnect?

I have a few tables where all the fields in a composite unique key are nullable (you cannot create a PK on nullable field). And such table does not have a PK.

Thanks,
Alex

MariiaI
Devart Team
Posts: 1472
Joined: Mon 13 Feb 2012 08:17

Re: Cannot modify a primary key member

Post by MariiaI » Tue 19 Mar 2013 09:29

The entity key for entity class should be generated based on:
- primary key of the table;
- if there is no primary key, the unique not null key is recognized as an entity key.

In case when entity classes don't have an entity key, they are not recognized as entities. Such entities can still be queried, but aren't cached, and change tracking is not enabled for them. LinqConnect does not allow modifications of such entities - an exception is raised when such entity is created or deleted, and updates of such entity are ignored.
To avoid this situation, you could mark any property of entity class as an Entity key and re-generate the code.

Please refer here http://www.devart.com/linqconnect/docs/ ... ntity.html

Post Reply