我通过一个实现
EntityConfiguration
的 IEntityTypeConfiguration<MyEntity>
类来配置我的实体。
对于正常应用程序执行,我使用 SQL Server,对于单元测试,我使用 SQLite。
问题是 SQLite 提供程序的功能有限,所以我想有条件地配置我的实体,以便如果它使用 SQL Server,它具有附加功能,例如
RowVersion
:
entity.Property(e => e.RowVersion)
.IsRequired(true)
.IsRowVersion()
.IsConcurrencyToken();
我如何知道正在使用哪个数据库提供商?
对问题的评论给出了为什么不在代码中执行此操作的充分理由 - 在测试中使用相同类型的数据库。
但是如果你仍然想这样做 - 我只能考虑将这个逻辑放在数据库上下文和实体类型配置中。请看下面的演示
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
using Microsoft.Extensions.DependencyInjection;
var serviceCollection = new ServiceCollection();
serviceCollection.AddDbContext<AppDbContext>(builder => builder.UseSqlServer("xxx"));
var serviceProvider = serviceCollection.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<AppDbContext>();
// trigger entity configuration
dbContext.Orders.ToList();
public class Orders
{
public int Id { get; set; }
public byte[] RowVersion { get; set; }
}
public class OrderConfiguration : IEntityTypeConfiguration<Orders>
{
private readonly string provider;
public OrderConfiguration(string provider)
{
this.provider = provider;
}
public void Configure(EntityTypeBuilder<Orders> builder)
{
builder.HasKey(x => x.Id);
if (provider == "SqlServer")
{
builder.Property(x => x.RowVersion)
.IsRequired(true)
.IsRowVersion()
.IsConcurrencyToken()
;
}
}
}
public class AppDbContext : DbContext
{
public DbSet<Orders> Orders { get; set; }
private readonly string provider;
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
var isSqlServer = options.Extensions.Any(x => x is SqlServerOptionsExtension);
if (isSqlServer)
{
provider = "SqlServer";
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// do this or load different configuration type for each provider
modelBuilder.ApplyConfiguration(new OrderConfiguration(provider));
base.OnModelCreating(modelBuilder);
}
}