Reputation: 25
I have a legacy database with the table which has only one row without a primary key. When I try to update this row nothing happens. I searched a lot and came on this line of code (dbf.Entry(nextPro).State = EntityState.Modified;)
. When I added this code I got the error: "Unable to track an instance of type 'NxtId' because it does not have a primary key. Only entity types with primary keys may be tracked."
I cannot remove the row and add a new one. I cannot add primary key. I have the only option to update the row somehow.
var nextPro = dbf.NxtId.FirstOrDefault();
nextPro.ProductNo = 239071;
dbf.Entry(nextPro).State = EntityState.Modified;
dbf.SaveChanges();
Entity:
public partial class NxtId
{
public int? ProductNo { get; set; }
public int? Uid { get; set; }
[Key]
public int? SatCode { get; set; }
}
Upvotes: 0
Views: 2167
Reputation: 25
The code that works for me (Entity Framework Core doesn't like to work with raw sql). So I had to find a command that still works.
using (SqlConnection connection = new SqlConnection(Configuration["ConnectionStrings:Test"]))
{
SqlCommand command = new SqlCommand("UPDATE dbo.NxtID SET ProductNo =" + newProductNo, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Upvotes: 1
Reputation: 19570
You cannot track or change an entity with Entity Framework when it does not have a key. However, you can still read data from the database. Also, you can run custom manually written SQL queries using the extension method RelationalDatabaseFacadeExtensions.ExecuteSqlRaw()
. Use it to send a normal UPDATE
query and then read the entity again from the database to get the new values.
dbf.Database.ExecuteSqlRaw($"UPDATE {nameof(NxtId)} SET {nameof(NxtId.ProductNo)} = {{0}}", 239071);
var nextPro = dbf.NxtId.Single();
Upvotes: 2