Entity Framework Core系列教程-18-断开模式下删除数据

Entity Framework Core 断开模式下删除数据

EF Core API会为EntityState为Deleted的实体建立并执行数据库中的DELETE语句。在EF Core中已连接和已断开连接的场景中删除实体没有什么区别。 EF Core使得从上下文中删除实体变得容易,而上下文又将使用以下方法删除数据库中的记录。

DbContext 方法DbSet 方法描述
DbContext.RemoveDbSet.Remove将指定的实体附加到状态为“已删除”的DbContext并开始对其进行跟踪
DbContext.RemoveRangDbSet.RemoveRange将实体的集合或数组附加到具有Deleted状态的DbContext并开始跟踪它们

以下示例演示了在断开连接的场景中删除实体的不同方法:

// entity to be deleted
var student = new Student() {
        StudentId = 1
};

using (var context = new SchoolContext()) 
{
    context.Remove<Student>(student);
   
    // or the followings are also valid
    // context.RemoveRange(student);
    //context.Students.Remove(student);
    //context.Students.RemoveRange(student);
    //context.Attach<Student>(student).State = EntityState.Deleted;
    //context.Entry<Student>(student).State = EntityState.Deleted;
    
    context.SaveChanges();
}

在上面的示例中,使用Remove()或RemoveRange()方法从上下文中删除了具有有效StudentId的Studnet实体。数据将从SaveChanges()上的数据库中删除。上面的示例在数据库中执行以下delete命令:

exec sp_executesql N'SET NOCOUNT ON;
DELETE FROM [Students]
WHERE [StudentId] = @p0;
SELECT @@ROWCOUNT;
',N'@p0 int',@p0=1
go

注意:EF Core中新引入了DbContext.Remove()和DbContext.RemoveRange()方法,以简化删除操作。

异常

如果相应数据库表中不存在Remove()或RemoveRange()方法中指定实体中的Key值,则EF Core将引发异常:以下示例将引发异常。

var student = new Student() {
    StudentId = 50
};

using (var context = new SchoolContext()) {
    context.Remove<Student>(student);
    context.SaveChanges();
}

在上面的示例中,数据库中不存在StudentId = 50的Student。因此,EF Core将引发以下DbUpdateConcurrencyException:

Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.
数据库操作预期会影响1行,但实际上会影响0行。自加载实体以来,数据可能已被修改或删除。

因此,您需要适当地处理以上异常,或者在删除ID之前确保数据库中存在具有ID的对应数据。

var student = new Student() {
    StudentId = 50
};

using (var context = new SchoolContext()) 
{
    try
    {
        context.Remove<Student>(deleteStudent);
        context.SaveChanges();
    }    
    catch (DbUpdateConcurrencyException ex)
    {
        throw new Exception("数据库中不存在此纪录");
    }
    catch (Exception ex)
    {
        throw;
    }
}

删除多条记录

您可以使用DbContext.RemoveRange()或DbSet.RemoveRange()方法一次性删除多个实体。

IList<Student> students = new List<Student>() {
    new Student(){ StudentId = 1 },
    new Student(){ StudentId = 2 },
    new Student(){ StudentId = 3 },
    new Student(){ StudentId = 4 }
};

using (var context = new SchoolContext()) 
{
    context.RemoveRange(students);
    
    // or
    // context.Students.RemoveRange(students);
    
    context.SaveChanges();
}

上面的示例将在单个数据库行程中从数据库中删除4条记录。因此,EF Core改善了性能。

exec sp_executesql N'SET NOCOUNT ON;
DELETE FROM [Students]
WHERE [StudentId] = @p0;
SELECT @@ROWCOUNT;


DELETE FROM [Students]
WHERE [StudentId] = @p1;
SELECT @@ROWCOUNT;

DELETE FROM [Students]
WHERE [StudentId] = @p2;
SELECT @@ROWCOUNT;


DELETE FROM [Students]
WHERE [StudentId] = @p3;
SELECT @@ROWCOUNT;

',N'@p0 int,@p1 int',@p0=1,@p1=2,@p2=3,@p3=4
go

删除关联数据

如果一个实体与其他实体有一对一或一对多的关系,则在删除根实体时删除相关数据取决于如何配置该关系。
例如,考虑“学生”和“年级”实体之间存在一对多关系。特定的GradeId将有许多学生记录。如果我们尝试删除数据库中具有相关学生记录的成绩,EF将抛出参考完整性错误。要解决此问题,您可以使用Fluent API定义引用约束操作选项。例如,您可以为该关系配置一个级联删除选项,如下所示。

modelBuilder.Entity<Student>()
    .HasOne<Grade>(s => s.Grade)
    .WithMany(g => g.Students)
    .HasForeignKey(s => s.GradeId)
    .OnDelete(DeleteBehavior.Cascade);

现在,如果您删除成绩实体,那么所有相关的学生记录也将在数据库中删除。
EF Core中还有其他引用约束操作选项,例如SetNull,ClientSetNull和Restrict。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Summary Entity Framework Core in Action teaches you how to access and update relational data from .NET applications. Following the crystal-clear explanations, real-world examples, and around 100 diagrams, you'll discover time-saving patterns and best practices for security, performance tuning, and unit testing. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology There's a mismatch in the way OO programs and relational databases represent data. Enti ty Framework is an object-relational mapper (ORM) that bridges this gap, making it radically easier to query and write to databases from a .NET application. EF creates a data model that matches the structure of your OO code so you can query and write to your database using standard LINQ commands. It will even automatically generate the model from your database schema. About the Book Using crystal-clear explanations, real-world examples, and around 100 diagrams, Entity Framework Core in Action teaches you how to access and update relational data from .NET applications. You'l start with a clear breakdown of Entity Framework, long with the mental model behind ORM. Then you'll discover time-saving patterns and best practices for security, performance tuning, and even unit testing. As you go, you'll address common data access challenges and learn how to handle them with Entity Framework. What's Inside Querying a relational database with LINQ Using EF Core in business logic Integrating EF with existing C# applications Applying domain-driven design to EF Core Getting the best performance out of EF Core Covers EF Core 2.0 and 2.1
C++是一种广泛使用的编程语言,它是由Bjarne Stroustrup于1979年在新泽西州美利山贝尔实验室开始设计开发的。C++是C语言的扩展,旨在提供更强大的编程能力,包括面向对象编程和泛型编程的支持。C++支持数据封装、继承和多态等面向对象编程的特性和泛型编程的模板,以及丰富的标准库,提供了大量的数据结构和算法,极大地提高了开发效率。12 C++是一种静态类型的、编译式的、通用的、大小写敏感的编程语言,它综合了高级语言和低级语言的特点。C++的语法与C语言非常相似,但增加了许多面向对象编程的特性,如类、对象、封装、继承和多态等。这使得C++既保持了C语言的低级特性,如直接访问硬件的能力,又提供了高级语言的特性,如数据封装和代码重用。13 C++的应用领域非常广泛,包括但不限于教育、系统开发、游戏开发、嵌入式系统、工业和商业应用、科研和高性能计算等领域。在教育领域,C++因其结构化和面向对象的特性,常被选为计算机科学和工程专业的入门编程语言。在系统开发领域,C++因其高效性和灵活性,经常被作为开发语言。游戏开发领域中,C++由于其高效性和广泛应用,在开发高性能游戏和游戏引擎中扮演着重要角色。在嵌入式系统领域,C++的高效和灵活性使其成为理想选择。此外,C++还广泛应用于桌面应用、Web浏览器、操作系统、编译器、媒体应用程序、数据库引擎、医疗工程和机器人等领域。16 学习C++的关键是理解其核心概念和编程风格,而不是过于深入技术细节。C++支持多种编程风格,每种风格都能有效地保证运行时间效率和空间效率。因此,无论是初学者还是经验丰富的程序员,都可以通过C++来设计和实现新系统或维护旧系统。3

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值