实体框架删除对象 - 并发错误(如何禁用并发)?
有没有办法禁用 EntityFramework 中抛出的并发错误?
例如:
using (xEntities5 entities = new xEntities5())
{
entities.Domains.MergeOption = System.Data.Objects.MergeOption.NoTracking;
Domain domain = new Domain() { DomainId = id };
EntityKey key = entities.CreateEntityKey(entities.CreateObjectSet<Domain>().EntitySet.Name, domain);
domain.EntityKey = key;
entities.Attach(domain);
//entities.AttachTo(entities.CreateObjectSet<Domain>().EntitySet.Name, domain);
entities.DeleteObject(domain);
return entities.SaveChanges(); // returns affected rows... must catch error?
}
有没有一种方法不必在 SaveChanges 周围进行 try/catch 来检测是否没有删除任何内容?
Is there a way to disable concurrency error thrown in EntityFramework?
For example:
using (xEntities5 entities = new xEntities5())
{
entities.Domains.MergeOption = System.Data.Objects.MergeOption.NoTracking;
Domain domain = new Domain() { DomainId = id };
EntityKey key = entities.CreateEntityKey(entities.CreateObjectSet<Domain>().EntitySet.Name, domain);
domain.EntityKey = key;
entities.Attach(domain);
//entities.AttachTo(entities.CreateObjectSet<Domain>().EntitySet.Name, domain);
entities.DeleteObject(domain);
return entities.SaveChanges(); // returns affected rows... must catch error?
}
Is there a way to not have to do try/catch around SaveChanges in order to detect if nothing was deleted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,您无法关闭并发错误。并发错误基于受影响的行数,因此如果您想要删除一行并且该行未被删除(例如因为它不再存在),则会引发并发异常。此外,
SaveChanges
在事务中工作,因此如果您想删除 5 行,但只删除了 4 行,则会引发异常并回滚所有删除。如果您使用标记为
ConcurrencyMode.Fixed
的列,并发测试可能会更加严格。这些列用于 SQL 语句的 where 条件,因此只能处理未修改的数据库记录。一旦出现并发异常,您就应该解决它。
As I know, you can't turn off concurrency error. Concurrency error is based on number of affected rows so if you want to delete a row and it is not deleted (for example because it doesn't exist any more) concurrency exception is fired. Moreover
SaveChanges
works in transaction so if you want to delete 5 rows and only 4 rows are deleted the exception is fired and all deletes are rolled back.Concurrency test can be even more restrictive if you use columns marked as
ConcurrencyMode.Fixed
. These columns are used in where condition of SQL statements so only unmodified database records can be processed.Once you get concurrency exception you are supposed to solve it.
SaveChanges()会抛出异常,并且不会在内部捕获它们,所以如果想继续执行,就必须使用try/catch。 SaveChanges() 还返回一个方法,其中包含提交到数据库的实体数量,也就是说,如果没有发生错误:-)
HTH。
SaveChanges() will throw exceptions and doesn't catch them internally, so if you want to continue execution, you have to use try/catch. SaveChanges() also returns a method with the number of entities committed to the database, that is, if no error occurred :-)
HTH.