使用EF按ID删除记录,如果ID不存在,则引发异常 [英] Use EF to delete a record by id, if id does not exist, an exception is thrown

查看:82
本文介绍了使用EF按ID删除记录,如果ID不存在,则引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

try
{
    Student stu = new Student() { ID = id };
    db.Entry(stu).State = EntityState.Deleted;

    int result = db.SaveChanges();
}
catch (DataException e)
{

}

例外是:

存储更新,插入或删除语句影响了意外行数(0).自从以来,实体可能已被修改或删除实体已加载.看 http://go.microsoft.com/fwlink/?LinkId=472540 有关的信息了解和处理乐观并发异常.

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

...但是我不想发生异常,我想获取受影响的行数,例如 0 .

...but I don't want to get an exception, I want get the number of affected rows, like 0.

推荐答案

如果您不介意从数据库中获取实体只是为了删除它们,则可以这样做

If you don't mind fetching the entities from database just to delete them, you could do

db.Students.RemoveRange(db.Students.Where(x => x.Id == ID));

如果您更关心获取条目数据,请使用以下一项检查是否存在,以ID方式删除.

If you are more concerned about fetching the entry data, use one of the check if exists, delete by ID ways.

如果您担心减少数据库往返次数,请使用类似于以下内容的自定义SQL命令(可能会转换为存储过程).

If you are concerned about reducing the amount of database roundtrips, use a custom SQL command similar to the following (maybe convert to stored procedure).

db.Database.ExecuteSqlCommand("delete from \"Schema\".\"Students\" where ID = @p0", id);

但是,如果您选择了最后一个示例,我认为您根本不应该使用EF.您失去了抽象,突然需要照顾SQL等中的模式和表名.

However, I think you shouldn't use EF at all, if the last example is your option. You lose abstraction and suddenly need to care for schema and table names in SQL etc.

这篇关于使用EF按ID删除记录,如果ID不存在,则引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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