C#:从 Net Core 中的 DbContext 继承,构造函数:没有为此 DbContext 配置数据库提供程序 [英] C#: Inherit from DbContext in Net Core, Constructor: No database provider has been configured for this DbContext

查看:61
本文介绍了C#:从 Net Core 中的 DbContext 继承,构造函数:没有为此 DbContext 配置数据库提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有如下的 PropertyApplication DbContext,

I currently have PropertyApplication DbContext as below,

public partial class PropertyContext : DbContext
{
    public PropertyContext()
    {
    }

    public PropertyContext(DbContextOptions<PropertyContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Address> Address { get; set; }
    public virtual DbSet<BoundaryChangeEvent> BoundaryChangeEvent { get; set; }

我想从这个 PropertyDbContext 继承.这是在构造函数中正确完成的吗?尝试通过下面的单元测试,它会覆盖保存更改以引入审核用户信息.只是好奇下面的构造函数语句是否特别正确?或者我应该尝试使用 AuditablePropertyContext 选项尝试下面的选项 2?

I would like to inheritance from this PropertyDbContext. Is this being done correctly in the constructor? Attempting to make unit test pass below, it overrides save changes to bring in auditing user information. Just curious if specifically the constructor statements below look correct? Or should I try to attempt option 2 below with AuditablePropertyContext options?

public class AuditablePropertyContext : PropertyContext
{
    private int _user;

    public AuditablePropertyContext()
    {
    }

    public AuditablePropertyContext(DbContextOptions<PropertyContext> options, UserResolverService userService)
        : base(options)
    {
        _user = userService.GetUser();
    }

    public void ApplyCreatedBy()
    {
        var modifiedEntities = ChangeTracker.Entries<ICreatedByUserId>().Where(e => e.State == EntityState.Added);
        foreach (var entity in modifiedEntities)
        {
            entity.Property("CreatedByUserId").CurrentValue = _user;
        }
    }

    public override int SaveChanges()
    {
        ApplyCreatedBy();
        return base.SaveChanges();
    }

}

选项 2:

我在尝试执行此操作时收到错误,

I was receiving error trying to conduct this,

public AuditablePropertyContext(DbContextOptions<AuditablePropertyContext> options, UserResolverService userService)
    : base(options)
{
    _user = userService.GetUser();
}

错误:

错误 CS1503 参数 1:无法从Microsoft.EntityFrameworkCore.DbContextOptions IPTS.PropertyManagement.Infrastructure.Auditable.Data.AuditablePropertyContext"转换为Microsoft.EntityFrameworkCore.DbContextOptions IPTS.PropertyManagement.Infrastructure.Data.Property>Context"

Error CS1503 Argument 1: cannot convert from 'Microsoft.EntityFrameworkCore.DbContextOptions IPTS.PropertyManagement.Infrastructure.Auditable.Data.AuditablePropertyContext' to 'Microsoft.EntityFrameworkCore.DbContextOptions IPTS.PropertyManagement.Infrastructure.Data.PropertyContext '

*有时公司使用 SQL Server,有时使用 InMemory 或 SQLite

*Sometimes company utilizes SQL Server, sometimes InMemory, or SQLite

单元测试失败:

services.AddSingleton(a =>
{
    var mock = new Mock<IUserResolverService>();
    mock.Setup(b => b.GetUser()).Returns(5);
    return mock.Object;
});

services.AddDbContext<PropertyContext>(
    options => options.UseInMemoryDatabase("Ipts").UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll),
    ServiceLifetime.Singleton);
services.AddSingleton<DbContext, PropertyContext>();


services.AddDbContext<AuditablePropertyContext>(
    options => options.UseInMemoryDatabase("Ipts").UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll),
    ServiceLifetime.Singleton);
services.AddSingleton<AuditablePropertyContext>();

services.RegisterMappingProfiles(new ApplicationServicesMappingProfile(),
    new PropertyManagementDataMappingProfile());
return services;

}

单元测试:错误

Message: 
System.InvalidOperationException : No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
Stack Trace: 
DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
DbContext.get_InternalServiceProvider()
DbContext.get_DbContextDependencies()

推荐答案

将构造函数PropertyContext类改成如下代码:

Change the constructor PropertyContext class to the following code:

public PropertyContext(DbContextOptions options)
        : base(options)
    {
    }

然后将构造函数AuditablePropertyContext 类更改为以下代码:

then change the constructor AuditablePropertyContext class to the following code:

  public AuditablePropertyContext(DbContextOptions options, UserResolverService userService)
        : base(options)
    {
        _user = userService.GetUser();
    }

注意: 不需要时删除两个类中的默认构造函数.

notice: Delete the default constructor in both classes when you don't need it.

这篇关于C#:从 Net Core 中的 DbContext 继承,构造函数:没有为此 DbContext 配置数据库提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆