Reputation: 429
I currently have a page that displays a list of settings. The table of data has 3 fields called Name(PK), BrandCode and Value. The data comes from a database which doesn't contain an ID field and within my application I want to be able to edit this data within all the fields if necessary. I am able to edit the BrandCode and Value but not the Name as it is set as the primary key. Is there a way around this so that I am also able to edit the Name field?
Model
[Table("Settings")]
public class ServiceSettings
{
[Key]
public string Name { get; set; }
public string BrandCode { get; set; }
public string Value { get; set; }
}
This is the error that I receive when i click Save Changes.
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded
If you require any more information then please let me know.
Thanks in advance.
Upvotes: 1
Views: 1432
Reputation: 137128
You can't edit the primary key field.
Your only solution that doesn't involve adding a specific ID field to the database is to create an id field in your model:
[Table("Settings")]
public class ServiceSettings
{
[Key]
public int Id { get; set; } // Created ID field
public string Name { get; set; }
public string BrandCode { get; set; }
public string Value { get; set; }
}
and populate it when you load your data.
It may be better to use a GUID
rather than an int
to ensure uniqueness.
Upvotes: 0
Reputation: 332
I am sharing just one of the suggestion or better approach :)
Please do not try to make name as PK
because it might contains same data.
You can also create temporary ID column and declare it as PK
If it is existing big database, where editing table is possible, So you can make
Name
asUnique key
and create anotherID
PK.
Hope this post will solve your issue :)
Upvotes: 0
Reputation: 361
If you have access to your database - create an Id column which you use as your key and set your Name column to Unique.
Updating a PK column is awful practice - don't do it.
I want to answer the question though.
If there is no other solution, a workaround (I'd call it hack) would be:
1) Save all your data from your row temporarily
2) Delete the row
3) Create a new row with all the updated values
If you have foreign keys, you'll also need to update them.
I would not recommend this solution though. Only use it if absolutely necessary. It is not without reason that PKs should not be updated.
Upvotes: 2