Don
Don

Reputation: 1

How to update primary key of Entity

Before you tell me that it is a bad idea to change the primary key of an entity, let me tell you I fully agree...

If I have an entity and try to change the primary key then, YES it is a bad idea for data integrity.

However, suppose you have an entity that is used to join two entities. Both entities have an Id (primary key). The entity that you want to change references the primary key of the other two. I want to change the reference to one of the entities (but it is defined as a primary key).

Example:

Class Customer
    Public Property Id As Integer
    Public Property Name as String
End Class

Class Address
    Public Property ID As Integer
    Public Property Description As String
End Class

Class CustomerAddressAssignments
    Public Property CustomerID As Integer
    Public Property Customer As Customer
    Public Property AddressID As Integer
    Public Property Address As Address
End Class

Configuration for Customer:
builder.ToTable("Customers").HasKey(Function(k) k.ID)
Configuration for Address:
builder.ToTable("Addresses").HasKey(Function(k) k.ID)
Configuration for CustomerAddressAssignments:
builder.ToTable("CustomerAddresses").HasKey(Function(k) New With {k.CustomerID, k.AddressID})

Now I have loaded a CustomerAddressAssignment and want to change the Customer/Address associated with this assignment.
How should I accomplish this? When I try to save the changes I get: The property 'CustomerAddressAssignment.AddressID' is part of a key and so cannot be modified or marked as modified.

Upvotes: 0

Views: 191

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

You're not changing a primary key; you're changing a foreign key? Your person is "moving house" by you changing which addressid the personid is mapped to, in the middleman table?

Just delete the old mapping and make a new one. Or even better, set the MovedOutOnDate property to DateTime.Now, and make a new mapping, and that way you have the person's entire address history maintained for future needs (and the person's current address(es) is defined as the one(s) where the MovedOutOnDate is null

If your mapping table starts storing more information or relating to other tables in and of itself (for example the order history table recording what person and what address was shipped to/billed to) then the table could have it's own single column PK, so that those other tables it relates to don't have a dual column FK

Upvotes: 1

Related Questions