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

查看:360
本文介绍了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.PropertyContext"

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天全站免登陆