SQL 解决方案:存储更新、插入或删除语句影响了意外的行数 (0)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6819813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Solution for: Store update, insert, or delete statement affected an unexpected number of rows (0)
提问by nosbor
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.
存储更新、插入或删除语句影响了意外的行数 (0)。自加载实体以来,实体可能已被修改或删除。刷新 ObjectStateManager 条目。
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
我阅读了主题: 实体框架:“存储更新、插入或删除语句影响了意外的行数 (0)。” 为了VMAtm,罗伯特·哈维
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?
当我删除此触发器时,我不会收到此异常。所以这个触发器是有问题的。现在我有一个问题——为什么?我应该做些什么吗?
回答by nosbor
Solution:
解决方案:
try {
context.SaveChanges();
} catch (OptimisticConcurrencyException) {
context.Refresh(RefreshMode.ClientWins, db.Articles);
context.SaveChanges();
}
回答by Prem Prakash
Its better you update your save method like this..... In case you calling savechange()
method of entity context after every addobject and deleteobject or modification :
最好像这样更新您的保存方法..... 如果您savechange()
在每次 addobject 和 deleteobject 或修改后调用实体上下文的方法:
public void Save(object entity)
{
using (var transaction = Connection.BeginTransaction())
{
try
{
SaveChanges();
transaction.Commit();
}
catch (OptimisticConcurrencyException)
{
if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Deleted || ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Modified)
this.Refresh(RefreshMode.StoreWins, entity);
else if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Added)
Detach(entity);
AcceptAllChanges();
transaction.Commit();
}
}
}
回答by Tim
It's because you have SET NOCOUNT ON
.
The EF SQL Statement that it generates ALWAYS adds a clause of where @@ROWCOUNT > 0 and [ID] = scope_identity()
(for example).
Notice the where @@ROWCOUNT > 0
clause. Take off your SET NOCOUNT ON
statement and it should work.
那是因为你有SET NOCOUNT ON
.
它生成的 EF SQL 语句总是添加一个子句where @@ROWCOUNT > 0 and [ID] = scope_identity()
(例如)。
注意where @@ROWCOUNT > 0
条款。去掉你的SET NOCOUNT ON
声明,它应该可以工作。
回答by Jboy Flaga
Possible Problem: You placed a ReadOnlyAttribute in you entity key's metadata, which causes its value to become zero
可能的问题:您在实体键的元数据中放置了 ReadOnlyAttribute,这导致其值变为零
[DisplayName("Student ID")]
[ReadOnly(true)]
public int StudentID { get; set; }
Solution: Remove the ReadOnlyAttribute
解决方案:删除 ReadOnlyAttribute
[DisplayName("Student ID")]
public int StudentID { get; set; }
回答by binjiezhao
I had the same problem, this error message is a rather mystifying one. The answer from webtrifusion helped me. See Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."
我有同样的问题,这个错误信息是一个相当神秘的信息。webtrifusion 的回答帮助了我。请参阅实体框架:“存储更新、插入或删除语句影响了意外的行数 (0)。”
It turns out I forgot to add "Id:0" in the JSON on the client side.
结果我忘记在客户端的 JSON 中添加“Id:0”。
回答by lloyd
I had InsertAsync setting EntityState to Modified implementing a Repository pattern. When Debugging I spotted the entity's idwas 0
我有 InsertAsync 将 EntityState 设置为 Modified 实现Repository pattern。调试时我发现实体的 id为 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;
回答by Kemal Can ?Z?EL?K
I had same error then I realized that I forgot the set primary key in table and setting increment values...
我有同样的错误然后我意识到我忘记了表中设置的主键并设置了增量值......
回答by Max CHien
In my case, need to set DatabaseGenerated Attribute when Custom Code First Conventions
在我的情况下,需要在自定义代码优先约定时设置 DatabaseGenerated 属性
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.
关闭数字主键的标识 以下示例将 DepartmentID 属性设置为 System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None 以指示该值不会由数据库生成。
modelBuilder.Entity<Department>().Property(t => t.DepartmentID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
see https://docs.microsoft.com/zh-tw/ef/ef6/modeling/code-first/conventions/custom
见https://docs.microsoft.com/zh-tw/ef/ef6/modeling/code-first/conventions/custom
and https://docs.microsoft.com/zh-tw/ef/ef6/modeling/code-first/fluent/types-and-properties
和https://docs.microsoft.com/zh-tw/ef/ef6/modeling/code-first/fluent/types-and-properties
回答by Prashant J
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. :)
解决方案:检查主键值是否通过以更新给定记录。:)
回答by user1656671
Using Entity Framework Code first,
首先使用实体框架代码,
using (MyDbContext db = new MyDbContext ( )) {..
使用 (MyDbContext db = new MyDbContext ()) {..
Adding this after the using line:
在 using 行之后添加:
db.Configuration.ValidateOnSaveEnabled = true;