首页 > 解决方案 > EF Core 单个 DELETE 语句

问题描述

在断开连接的情况下,我有以下模型:

public class Module
{
    public Module()
    {
        Students = new List<Student>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }

    public List<Student> Students { get; set; }
}

public class Student
{
    public Student()
    {
        Modules = new List<Module>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }

    public List<Module> Modules { get; set; }
}

我正在调用 RemoveStudents 并在下面传递两个学生 ID 以从模块中删除一些学生

public void RemoveStudents(List<long> studentIds)
{
    var module = (from dbModule in dbContext.Module.Include(x => x.Students)
                  select dbModule).SingleOrDefault(x => x.Id == 1);

    module.Students.RemoveAll(x => studentIds.Contains(x.Id));

    dbContext.SaveChanges();
}

我可以看到它生成两个删除查询(每个学生一个)。

DELETE FROM [ModuleStudent]
WHERE [ModulesId] = @p0 AND [StudentsId] = @p1;

出于性能原因,SQL 中最好编写一个包含所有 Id 的查询:

DELETE FROM [ModuleStudent]
WHERE [ModulesId] = @p0 AND [StudentsId] IN (@p1, @p2, @p3.....);

如何“强制” EF 使用多个参数生成删除?

标签: c#.net.net-coreentity-framework-core

解决方案


推荐阅读