繁体   English   中英

使用 ef core 软删除一组行的正确方法是什么?

[英]What is the right way to soft delete a set of rows using ef core?

我有一个数据库,其中包含一个关于一些用户的表。

架构如下所示:

 User : (id, name, username, email, phone, when_deleted)

我使用 ef core 从 asp.net 核心应用程序与此表进行交互。 实体 class 如下。

 public class User
    {
        public int id { get; set; }
        public string name { get; set; }
        public string username { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
    }

我有 ASP.NET 核心后台服务,它向供应商 REST API 端点发送 GET 请求,以提供有关用户的最新信息。

[
{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
      "phone": "1-770-736-8031 x56442"
  },
{
    "id": 2,
    "name": "Jhon Doe",
    "username": "JDoe",
    "email": "Jdoe@april.biz",
      "phone": "1-404-536-8031 x56442"
  }
]

可以在 API 端删除用户,但在我这边我不想删除它们,我只想软删除或使用标志将它们标记为已删除,例如 when_deleted。

我怎样才能以正确的方式做到这一点?

一种方法是通过Global Filter Queries

全局查询过滤器是 LINQ 查询谓词应用于元数据 model 中的实体类型(通常在 OnModelCreating 中)。 查询谓词是 boolean 表达式,通常传递给 LINQ Where 查询运算符。 EF Core 自动将此类过滤器应用于涉及这些实体类型的任何 LINQ 查询。 EF Core 还将它们应用于实体类型,通过使用 Include 或导航属性间接引用。 此功能的一些常见应用是:

软删除 - 实体类型定义 IsDeleted 属性。

您可以将when_deleted属性添加到User实体。 请注意,我使用的是DateTime? 这里是因为属性的名称让我相信它是DateTime 如果这是您想要的,那么修改它以使其成为bool应该很容易。

public class User
{
    public int id { get; set; }
    public string name { get; set; }
    public string username { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    // The when_deleted property needs to be a nullable DateTime since an
    // entity that is not deleted will not have a when_deleted value.
    public DateTime? when_deleted { get; set; }
}

然后,当您配置实体类型时(通常在OnModelCreating上的DbContext ),您将指定过滤器查询。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().HasQueryFilter(u => u.when_deleted == null);
}

现在,每当您查询User实体时,只会返回when_deleted属性为null的实体。

当您检测到User已被删除时,无需将其从DbSet中删除,只需将when_deleted属性设置为DateTime.UtcNowDateTime.Now ,以适合您的情况为准。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM