Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

c# - The property 'name' is part of the object's key information and cannot be modified. Entity Framework

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...