0

I am trying to update an existing entity using the following code. Getting the error :

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

Not sure what I am doing wrong. Can anyone please help me with this? Find below my code:

var record = await (from c in context.Customers
   where c.Id == input.Id
   select c)
   .AsNoTracking()
   .FirstOrDefaultAsync<Customer>();

if (record == null)
{
   // New record 
   context.Customers.Add(input);
}
else
{
   // Existing record 
   context.Customers.Attach(record);
   context.Entry(record).CurrentValues.SetValues(input);
   record.SetUpdateInfo(user.UserId);
}   
croxy
  • 3,966
  • 8
  • 29
  • 43
Mukil Deepthi
  • 5,114
  • 12
  • 58
  • 115

1 Answers1

1

If your input has an Id set, Entity Framework is going to try and create an entity with that Id. Try setting the Id of input to 0 if its not found and add the record.

Phil Hess
  • 41
  • 1