Click here to Skip to main content
15,890,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Guys

I am currently having an issue with the following.

I am using the entity framework with mvc and i am trying to save some data according to the model.

So this is the process that currently takes place from a user perspective
Users create a record
Save a record
and have the ability to copy the record with one or two updates and save as a new record.

Issue i am having is when they try to save the first record there is a method which generates the key for the record, the record saves with no issues. if the user tries to copy and save once the key is generated and i try to add the record i am getting the following error "The property is part of the object's key information and cannot be modified"

What I have tried:

This is my current code

C#
public void Add(Customer entity)
        {
            
            if (entity.PortalId == new Guid("{00000000-0000-0000-0000-000000000000}"))
            {
         
                entity.PortalId = Guid.NewGuid();
            }
            this.DbContext.Suppliers.Add(entity);
         
        }
Posted
Updated 13-Sep-16 22:06pm
Comments
johannesnestler 14-Sep-16 9:37am    
let the database generate your key! - so this problem will resolve itself, or remove the key Attribute (or convention) from your model-Code (not recommend that) and handle the keys on your own - but again: DONT!
johannesnestler 15-Sep-16 10:17am    
but why don't you let the database generate the key?

1 solution

Try removing the if statement and just generate a new ID.
 
Share this answer
 
Comments
IsiR_19 14-Sep-16 4:25am    
The new id is generated and updated before the add
sifiso.m 14-Sep-16 4:28am    
Before you add.

entity.PortalId = Guid.NewGuid();
this.DbContext.Suppliers.Add(entity);

should work.
IsiR_19 14-Sep-16 4:48am    
have tried it and still giving me the same error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900