I am trying to update a record and I get this error message after the context.SaveChanges();
The property 'name' is part of the object's key information and cannot be modified.
Here is the code for the update function:
if (context.EAT_SourceNames.Any(e => e.name == newSourceName))
{
MessageBox.Show("Name already exists in the Database");
}
else
{
var nameToUpdate = context.EAT_SourceNames.SingleOrDefault(e => e.name == sourceName.name);
if (nameToUpdate != null)
{
nameToUpdate.name = newSourceName;
context.SaveChanges();
RefreshDGVs();
}
}
My SourceNames
class looks like the following:
public EAT_SourceNames()
{
this.EAT_Sources = new ObservableListSource<EAT_Sources>();
}
public string name { get; set; }
public string version_id { get; set; }
public string allocation_name { get; set; }
I searched for similar questions, but could not find any working solution.
The only way I can think to update a text primary key is by using the following.
I do not believe it is best practice to use a "functional" primary key. A primary key's purpose is simply to uniquely identify a row.
See the answer from yildizm85 to this question: entity framework not working on table without identity column
"Entity Framework requires a Primary Key to generate a model from the database. If there is no Primary Key on a table it will simply select the non-nullable columns as a concatenated primary key and the Entity will be read/only."
Looking at your
EAT_SourceNames
object it appears there is no primary key field so the Entity Framework is using the column 'name' as part of the composite key which means it is read-only.The solution would be to add a Primary Key field to
EAT_SourceNames
and then your 'name' field would no longer be part of the primary key.Here is the proper solution of it.
You have to unchecked entity key of Name from your EAT_SourceNames.
You can do this by following steps.
Probably
name
is a part or full Primary Key for yourEAT_SourceNames
entity. You cannot modify object's PK, is it EF's limitation (see this thread).The point is that you work with an object. The "name" property identifies the object, that's why you can't modify it. The solution is to modify the value in the table with a SQL statement (UPDATE) and reload the context. Sincerely.
Same happened to me today. I set new entity's ID with the old record's ID and the error is gone.