# 9.4、增删改操作

## 新增操作

### 新增一条数据，无需返回（推荐）

```csharp
// 方式一，推荐
_testRepository.Insert(new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    });

// 方式二
_testRepository.Entity.Add(new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    });
```

### 新增一条数据，并立即返回新增实体（推荐）

```csharp
// 方式一，推荐
var newEntity = _testRepository.InsertWithSaveChanges(new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    });
var newId = _testRepository.Id; // 最新Id

// 方式二
var newEntity = _testRepository.Entity.Add(new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    });
_testRepository.SaveChanges();
var newId = _testRepository.Id;
```

### 新增多条数据，无需返回

```csharp
var addEntities = new List<TestEntity>(){
    new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    },
    new TestEntity()
    {
        Name = "MonkSoul",
        CreatedTime = DateTime.Now
    },
};
_testRepository.Insert(addEntities);
```

### 新增多条，并立即返回新增实体集合

```csharp
var addEntities = new List<TestEntity>(){
    new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    },
    new TestEntity()
    {
        Name = "MonkSoul",
        CreatedTime = DateTime.Now
    },
};
_testRepository.InsertWithSaveChanges(addEntities);
```

### 异步新增

```csharp
await _testRepository.InsertAsync(new TestEntity()
    {
        Name = "Monk",
        CreatedTime = DateTime.Now
    });
```

### 补充说明

新增操作包含两种：

1. `Insert`
2. `InsertWithSaveChanges`

它们的主要区别在于是否立即调用了 `dbContext.SaveChanges()` 方法。

## 更新操作

### 更新所有列，先查询实体

```csharp
var entity = _testRepository.Find(1);
entity.Name = "MonkSoul";
entity.Age = 27;
```

这种方式，无需调用 `_testRepository.Update(entity)` 和  `_testRepository.SaveChanges()`方法。但是会生成**更新所有列的 `Sql`**

### 更新指定列，先查询实体

```csharp
var entity = _testRepository.Find(1);
entity.Name = "MonkSoul";
entity.Age = 27;
_testRepository.SetModifyProperties(specEntity,
                                               u => u.Name,
                                               u => u.Age);
```

这种方式，无需调用 `_testRepository.Update(entity)` 和  `_testRepository.SaveChanges()`方法。但是会生成**更新指定列的 `Sql`**，比如这里是 `Name` 和 `Age` 两个属性

### 更新所有列，无需查询

```csharp
var entity = new Entity { Name ="Monk", Age = 27, Id = 1};
_testRepository.EntityEntryState(entity) =  EntityState.Modified;
```

注意：**必须包含主键 Id**

### 更新指定列，无需查询

```csharp
var entity = new Entity { Name ="Monk", Age = 27, Id = 1};
_testRepository.Context.Attach(entity);
_testRepository.SetModifyProperties(entity,
                                           u => u.Name,
                                           u => u.Age);
```

注意：**必须包含主键 Id**

### **更新所有列，先查询实体，并立即执行**

```csharp
var entity = _testRepository.Find(1);
entity.Name = "MonkSoul";
entity.Age = 27;

_testRepository.UpdateWithSaveChanges(entity);
```

### 更新多条实体，先查询出全部实体

```csharp
var entities = _testRepository.GetAll(u = > u.Id > 100);
foreach(var entity in entities){
    entity.Age = entity.Age + 1;
}
```

这种方式，无需调用 `_testRepository.Update(entity)` 和  `_testRepository.SaveChanges()`方法。

### 更新多条实体，先查询出全部实体，并立即执行

```csharp
var entities = _testRepository.GetAll(u = > u.Id > 100);
foreach(var entity in entities){
    entity.Age = entity.Age + 1;
}
_testRepository.UpdateWithSaveChanges(entities);
```

### 补充说明

更新操作包含两种：

1. `Update`
2. `UpdateWithSaveChanges`

它们的主要区别在于是否立即调用了 `dbContext.SaveChanges()` 方法。

## 删除操作

### **根据主键Id删除**

```csharp
_testRepository.Delete(1);
```

### 根据主键Id删除，并立即执行

```csharp
_testRepository.DeleteWithSaveChanges();
```

### 根据查询的实体删除

```csharp
var entity = _testRepository.Find(1);
_testRepository.Delete(entity);
```

### 根据查询的实体删除，并立即执行

```csharp
var entity = _testRepository.Find(1);
_testRepository.DeleteWithSaveChanges(entity);
```

### 根据多条已查询的实体删除

```csharp
var entities = _testRepository.GetAll(u = > u.Id > 100);
_testRepository.Delete(entities);
```

### 根据多条已查询的实体删除，并立即执行

```csharp
var entities = _testRepository.GetAll(u = > u.Id > 100);
_testRepository.DeleteWithSaveChanges(entities);
```

### 补充说明

删除操作包含两种：

1. `Delete`
2. `DeleteWithSaveChanges`

它们的主要区别在于是否立即调用了 `dbContext.SaveChanges()` 方法。

## 假删除/软删除

### 根据主键Id假删除

```csharp
_testRepository.FakeDelete(1, u => u.Void, 0);
```

### 根据主键Id假删除，并立即执行

```csharp
_testRepository.FakeDeleteWithSaveChanges(1, u => u.Void, 0);
```

### 根据条件假删除

```csharp
_testRepository.FakeDelete(u => u.Id == 1, u => u.Void, 0);
```

### 根据条件假删除，并立即执行

```csharp
_testRepository.FakeDeleteWithSaveChanges(u => u.Id == 1, u => u.Void, 0);
```

### 补充说明

假删除操作包含两种：

1. `FakeDelete`
2. `FakeDeleteWithSaveChanges`

它们的主要区别在于是否立即调用了 `dbContext.SaveChanges()` 方法。

## 新增或更新

### 新增或更新

```csharp
_testRepository.InsertOrUpdate(entity);
```

新增或更新，并立即执行

```csharp
_testRepository.InsertOrUpdateWithSaveChanges(entity);
```

### 补充说明

新增或更新操作包含两种：

1. `InsertOrUpdate`
2. `InsertOrUpdateWithSaveChanges`

它们的主要区别在于是否立即调用了 `dbContext.SaveChanges()` 方法。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monksoul.gitbook.io/hoa/shujukucaozuoshinan/zengshangaicaozuo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
