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.
Graduated with BSc(hons) in Information Systems in 1992 and have had to learn pretty much everything on the job since then.
Currently: Software Developer (Oracle, .NET and Javascript).
Used to be: Developer (SQL Server and .NET), Analyst(Using Oracle, SAS, Excel...) and before that a SQLServer 2000 DBA, Microsoft XAL developer.
Main skill set includes SQL Server, PL/SQL, C#, Javascript, VB .NET, Access, Excel, Word - VBA, SAS...
Interests include reading and things that fly.
I am a keen origami(paper folding) amateur.
Was once a classical guitarist, however Metallica have corrupted my tastes.
I run teboweb.com as a hobby