没有选择和乐观并发的实体框架删除 [英] Entity Framework delete without select and Optimistic Concurrency

查看:27
本文介绍了没有选择和乐观并发的实体框架删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Entity Framework删除一条记录(如果该记录存​​在的话)-我想生成类似的内容

I am trying to delete a record if it exists using Entity Framework - I want to generate something like

delete from tbl where id = 1

我不在乎是否存在任何记录,我只想删除它们.我应该可以不用先选择它们就可以这样做:

I don't care whether any records exist, I just want to delete them if they do. I should be able to do with without selecting them first like this:

var record = new tbl { id = 1, rel = new tbl_related { tbl_id = 1 } };
context.tbl.Attach(tbl);
context.tbl.Remove(tbl);
context.SaveChanges();

语法可能不完全存在,因为这不是复制和粘贴,并且我添加了外键关系以表明我已将其考虑在内.

The syntax might not exactly be there because this isn't a copy and paste, and I've added the foreign key relationship to show that I'm taking this into account.

在运行此代码时,EF将生成并运行正确的SQL,但我得到一个System.Data.Entity.Infrastructure.DbUpdateConcurrencyException,说存储更新,插入或删除语句影响了意外的行数(0).自加载实体以来,可能已被修改或删除."

On running this code the correct SQL is generated by EF and run but I get a System.Data.Entity.Infrastructure.DbUpdateConcurrencyException saying "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded".

但是,我完全希望很多时候可以删除零行.关于如何解决这个问题有什么想法吗?

However, I'm fully expecting zero rows to be deleted a lot of the time. Any ideas on how I can get around this?

我已经指出如何忽略DbUpdateConcurrencyException删除实体作为可能的副本时.这建议处理我现在正在做的DbUpdateConcurrencyException(并忽略),但是该帖子谈到了尝试删除可能已删除的行-我想删除可能永远不存在的行.我知道这可能只是语义上的问题,因为分辨率是相同的,但是我想强调一点,就是我所做的事情我认为是完全合理的,而Framework不能很好地处理它.

I've been pointed to How to ignore a DbUpdateConcurrencyException when deleting an entity as a possible duplicate. This suggests handling the DbUpdateConcurrencyException which I am now doing (and ignoring), but that post talks about trying to delete rows that might have been deleted - I want to delete rows that might never have existed. I know this might just be a question of semantics because the resolution is the same but I want to highlight that I am doing something that I see as perfectly reasonable and the Framework is not handling it very well.

谢谢

推荐答案

在EF上有扩展名github ,允许您通过一次调用数据库来更新和删除实体.

There is an extension for EF on github that allows you to update and delete entities with a single call to the database.

使用此扩展程序,您可以执行以下操作:

With this extension you can do something like this:

context.tbl.Delete(t => t.Id == 1);

一次调用应消除DbUpdateConcurrencyException.

A single call should eliminate your DbUpdateConcurrencyException.

这篇关于没有选择和乐观并发的实体框架删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆