Solution for: Store update, insert, or delete stat

2019-01-05 00:46发布

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?

9条回答
家丑人穷心不美
2楼-- · 2019-01-05 01:44

I had same error then I realized that I forgot the set primary key in table and setting increment values...

查看更多
戒情不戒烟
3楼-- · 2019-01-05 01:48

I found this error when i updating entity and forgot to pass Primary key value....

So Entity can update record with reference with Primary key

Solution : Check whether primary key value is pass or not to update the given record. :)

查看更多
家丑人穷心不美
4楼-- · 2019-01-05 01:51

I had InsertAsync setting EntityState to Modified implementing a Repository pattern. When Debugging I spotted the entity's id was 0

    public async Task InsertAsync(T entity)
    {

        dbContext.Entry(entity).State = EntityState.Modified;
        await dbContext.SaveChangesAsync();
    }

Changing the Entity State to Added fixed it.

    dbContext.Entry(entity).State = EntityState.Added;
查看更多
登录 后发表回答