Click here to Skip to main content
15,881,882 members
Articles / Database Development / SQL Server
Tip/Trick

Entity Framework Not Inserting Rows into SQL Server Database Table

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
25 Feb 2018CPOL 12.1K   4   4
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)


Written By
Software Developer
United Kingdom United Kingdom
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

Comments and Discussions

 
QuestionThank you so much Pin
Azim Zahir15-Feb-22 15:36
Azim Zahir15-Feb-22 15:36 
AnswerRe: Thank you so much Pin
GuyThiebaut15-Feb-22 19:05
professionalGuyThiebaut15-Feb-22 19:05 
PraiseThanks Pin
Сергій Ярошко25-Feb-18 6:54
professionalСергій Ярошко25-Feb-18 6:54 
GeneralRe: Thanks Pin
GuyThiebaut26-Feb-18 3:03
professionalGuyThiebaut26-Feb-18 3:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.