# 9.13、其他操作

## 获取操作上下文

```csharp
_testRepository.Context; // 返回 HoaDbContext 对象
```

## 获取DbSet 实体

```csharp
_testRepository.Entity;
```

## 获取Database 操作对象

```csharp
_testRepository.Database;
```

## 获取 EntityEntry 对象

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

获取此对象可以操作 `State` 实体状态。

## 获取 EntityState 对象

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

## 获取 DbConnection 对象

```csharp
_testRepository.DbConnection;

// 获取连接字符串
_testRepository.DbConnection.ConnectionString;

// 获取数据库名称
_testRepository.DbConnection.Database;
```

## 解析连接字符串信息

数据库连接字符串

```
Server=localhost;Database=Hoa;User=sa;Password=000000;
```

```csharp
// 获取数据库连接字符串中的 登录用户名
_testRepository.ConnectionStringDictionary["User"]; // => sa

// 获取数据库连接字符串中的 服务器地址
_testRepository.ConnectionStringDictionary["Server"]; // => localhost
```

## 动态切换仓储表

```csharp
_testRepository.ChangeTable("User");
```

## 输出EF Core 查询生成的 Sql 语句

```csharp
var sql = _testRepository.GetAll(u => u.Id > 1).ToSql();
Console.WriteLine(sql); // => select * from test where Id > 1;
```

## 提交更改

```csharp
_testRepository.SaveChanges();
```

## 是否设置了主键Key

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

## 获取所有数据库上下文

```
_testRepository.GetDbContexts();
```

## 将所有数据库上下文操作都保存

```
_testRepository.SavePoolChanges();
```
