Solution for: Store update, insert, or delete statement affected an unexpected number of rows (0)

Viewed 103516

I found a solution for people who get an exception:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

But, anyway I have question.

I read topic: Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)." To VMAtm, Robert Harvey

In my case I had for example table articles:

Articles
------------
article_id
title
date_cr
date_mod
deleted

And I had trigger:

create trigger articles_instead_of_insert 
on articles instead of insert 
as      
    SET NOCOUNT ON;
    insert into articles(
        article_id, 
        title, 
        date_cr,
        date_mod, 
        deleted
    )
    select 
        user_id, 
        title, 
        isnull(date_cr, {fn NOW()}),
        isnull(date_mod, {fn NOW()}),
        isnull(deleted, 0)
    from inserted;
go

When I delete this trigger then I dont get this exception. So this trigger is problem. And now I have a question - Why? Should I do something?

11 Answers

In my case, need to set DatabaseGenerated Attribute when Custom Code First Conventions

public class Car
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Model { get; set; }
    public DateTime Registered { get; set; }
}

or

Switching off Identity for Numeric Primary Keys The following example sets the DepartmentID property to System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None to indicate that the value will not be generated by the database.

modelBuilder.Entity<Department>().Property(t => t.DepartmentID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

see https://docs.microsoft.com/zh-tw/ef/ef6/modeling/code-first/conventions/custom

and https://www.learnentityframeworkcore.com/configuration/data-annotation-attributes/databasegenerated-attribute

and https://docs.microsoft.com/zh-tw/ef/ef6/modeling/code-first/fluent/types-and-properties

When using RowVersion as Tracking Property, to control concurrency in multi-user system, RowVersion which is auto generated by database engine by default, should be passed as Hidden Field in the view when Editing/Updating a record, the same way we manage the Key Identity Field:

@using (Html.BeginForm()) {
    @Html.HiddenFor(model => model.ID)
    @Html.HiddenFor(model => model.RowVersion) 
}
Related