Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Entity Framework Not Inserting Rows into SQL Server Database Table

5.00/5 (1 vote)
25 Feb 2018CPOL 12.9K  
Solving the Store update, insert, or delete statement affected an unexpected number of rows (0) response.

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:

C#
[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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)