|
|
# 说明
|
|
|
========
|
|
|
EF Core 7的学习总结项目。
|
|
|
|
|
|
## 使用 工厂对象(AddDbContextFactory)时,多构建函数时,IoC获取对象时会异常
|
|
|
在使用扩展方法 AddDbContextFactory()注册服务时,如果 DbContext有多个构建函数,会在获取服务时因为不知道使用哪个构建函数而异常。
|
|
|
|
|
|
解决方案:
|
|
|
+ 不要使用多构造函数
|
|
|
+ 合并成一个构建函数:比如统一使用 DbContextOptions<T> 参数,非IoC可以手动构建 DbContextOptions<T> 对象当参数
|
|
|
+ 使用 ActivatorUtilitiesConstructor 特性,指定IoC使用的构造函数
|
|
|
```csharp
|
|
|
public class AppDbContext : DbContext
|
|
|
{
|
|
|
private string? _connectString;
|
|
|
|
|
|
public AppDbContext()
|
|
|
{
|
|
|
|
|
|
}
|
|
|
|
|
|
public AppDbContext(string? connectstring, string dd = "dd")
|
|
|
{
|
|
|
_connectString = connectstring;
|
|
|
}
|
|
|
|
|
|
//指定IoC使用的构造函数
|
|
|
[ActivatorUtilitiesConstructor]
|
|
|
public AppDbContext(DbContextOptions<AppDbContext> options)
|
|
|
: base(options)
|
|
|
{
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
|
{
|
|
|
if (!optionsBuilder.IsConfigured)
|
|
|
{
|
|
|
if (string.IsNullOrWhiteSpace(_connectString))
|
|
|
{
|
|
|
_connectString = @"Server=127.0.0.1\SQL2019;Database=EFCore7Study;User Id=sa;Password=xxxx;Encrypt=True;TrustServerCertificate=True;";
|
|
|
}
|
|
|
|
|
|
optionsBuilder
|
|
|
.UseSqlServer(_connectString)
|
|
|
.EnableSensitiveDataLogging();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
|
{
|
|
|
modelBuilder.Entity<Account>().ToTable("Account");
|
|
|
|
|
|
base.OnModelCreating(modelBuilder);
|
|
|
}
|
|
|
|
|
|
public DbSet<Account> Accounts { get; set; }
|
|
|
}
|
|
|
```
|
|
|
|
|
|
## SQL Server 2008 分页错误
|
|
|
原因:EF Core 放弃了对SQL2008的支持,特别是分页查询会报错:"OFFSET 附近有语法错误",原因是OFFSET的分页语法,从SQL Server 2012开始支持。
|
|
|
|
|
|
解决:使用第三方库 "EntityFrameworkCore.UseRowNumberForPaging", 在SQL 2008中改用 Row_Number() 分页. 如下方式配置项目使用:加一个 .UseRowNumberForPaging()
|
|
|
|
|
|
```csharp
|
|
|
//原使用方法
|
|
|
xx.UseSqlServer(ConnectString, opt => {})
|
|
|
|
|
|
//修改后的使用方法
|
|
|
.UseSqlServer(ConnectString, opt => { opt.UseRowNumberForPaging(); })
|
|
|
```
|