The property 'AccountNumber' is part of the object's key information and cannot be modified

c# entity-framework entity-framework-6

Accepted Answer

3/5/2017 6:38:36 PM

Popular Answer

In light of your upgrade, you must consider the lifespan of yourDbContext . ADbContext will by default attempt to store any modifications made to any entities it is aware of when you callSaveChanges() .

So it seems that you are defining an in this example.DbContext working with you someplaceCustomer then collaborating with yourCustomerLookup all the while theDbContext is present and aware of your entities (e.g. it will be aware of any entity you retrieve from the database). next time you callSaveChanges() It is making an effort to preserve all that has altered.

Typically, you wish to produce and discardDbContexts just when you need them. They are portable, and you usually want them to last for a whole unit of work (whatever that may be in your app). Make it a habit to enclose your usage of them.using blocks to keep everything tidy. As a result, your approach may be as follows:

public void CreateCustomerLookUp(CustomerLookUp customerLookUp)
    using (var context = new CustomerContext())
        customerLookUp.LastUpdated = DateTime.Now;

        var encryptedCustomerLookUp = EncryptCustomerLookUp(customerLookUp);

        var newCustomerLookup = new CustomerLookUp()
            AccountNumber = encryptedCustomerLookUp.AccountNumber,
            EmailAddress = encryptedCustomerLookUp.EmailAddress,
            MobileNumber = encryptedCustomerLookUp.MobileNumber,
            UmbracoMemberId = encryptedCustomerLookUp.UmbracoMemberId,
            UpdateCode = encryptedCustomerLookUp.UpdateCode,
            UpdateNotification = encryptedCustomerLookUp.UpdateNotification

        context.Entry(customerLookUp).State = EntityState.Modified;


  1. To similarly localize, you'll also need to make adjustments elsewhere in your code.DbContexts Making the aforementioned adjustment alone will lead to 2DbContexts being active, you can still have additional tracking problems.

  2. With a little restructuring, you may be able to further limit the scope inside the procedure. Since I notice that you are changing 2 entities, I have encapsulated the whole function.customerLookup and newCustomerLookup ) and I have no idea what you're up to inEncryptCustomerLookup .

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow