9.13、其他操作
一些不常用的数据库操作,但又能解决很多奇葩的业务需求。
获取操作上下文
_testRepository.Context; // 返回 HoaDbContext 对象
获取DbSet 实体
_testRepository.Entity;
获取Database 操作对象
_testRepository.Database;
获取 EntityEntry 对象
_testRepository.EntityEntry(entity);
获取此对象可以操作 State
实体状态。
获取 EntityState 对象
_testRepository.EntityEntryState(entity);
获取 DbConnection 对象
_testRepository.DbConnection;
// 获取连接字符串
_testRepository.DbConnection.ConnectionString;
// 获取数据库名称
_testRepository.DbConnection.Database;
解析连接字符串信息
数据库连接字符串
Server=localhost;Database=Hoa;User=sa;Password=000000;
// 获取数据库连接字符串中的 登录用户名
_testRepository.ConnectionStringDictionary["User"]; // => sa
// 获取数据库连接字符串中的 服务器地址
_testRepository.ConnectionStringDictionary["Server"]; // => localhost
动态切换仓储表
_testRepository.ChangeTable("User");
输出EF Core 查询生成的 Sql 语句
var sql = _testRepository.GetAll(u => u.Id > 1).ToSql();
Console.WriteLine(sql); // => select * from test where Id > 1;
提交更改
_testRepository.SaveChanges();
是否设置了主键Key
_testRepository.IsKeySet(entity);
获取所有数据库上下文
_testRepository.GetDbContexts();
将所有数据库上下文操作都保存
_testRepository.SavePoolChanges();
最后更新于
这有帮助吗?