Introduction
In Entity Framework with SQL Server, you may receive the "Store update
, insert
, or delete
statement affected an unexpected number of rows (0)" response when you insert new rows using the Add
method for your database context.
This tip documents how I resolved this issue when I encountered it.
Background
I hit this issue when I was trying to add a new row to a SQL Server database table.
The issue was that I was missing one annotation after the [Key]
annotation in the model.
Using the Code
Ensure that you add the [DatabaseGenerated(DatabaseGeneratedOption.None)]
annotation to your model if you are setting the primary key within your code:
[Table("animal")]
public class Animal
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int idAnimal { get; set; }
public string Species { get; set; }
}
Points of Interest
Finding this information took me around two hours of reading many posts as well as documentation online.
So I thought I would post a solution here so that, both for my own benefit in future as well as for the benefit of others, this solution is documented online.