2

我正在尝试将 Entity Framework Core 与 ASP.NET Boilerplate .NET Core 一起使用,但我不想使用 Repository 内置函数。

我的数据库上下文有问题;它不断返回:

System.ArgumentNullException:“值不能为空。”

对于DbContext如下所示的实例:

public class MainProjectsAppService : ApplicationService
{
    private readonly DecentralizationDbContext _ctx;

    public MainProjectsAppService(IDbContextProvider<DecentralizationDbContext> dbContextProvider)
    {
        _ctx = dbContextProvider.GetDbContext();
    }

    public void CustomizedCreateMainProject(MainProject mainProject)
    {
        MainProject customizedMainProject = new MainProject
        {
            ...
        };

        _ctx.MainProjects.Add(customizedMainProject);
        _ctx.SaveChanges();
    }
}

我的代码截图

下面是DbContext类代码:

namespace Decentralization.EntityFrameworkCore
{
    public class DecentralizationDbContext : AbpZeroDbContext<Tenant, Role, User, DecentralizationDbContext>
    {
        /* Define a DbSet for each entity of the application */

        public DbSet<MainProject> MainProjects { get; set; }
        public DecentralizationDbContext(DbContextOptions<DecentralizationDbContext> options)
            : base(options)
        {
        }
    }
}
4

1 回答 1

3

不要dbContextProvider.GetDbContext()在构造函数中调用。

而是定义一个吸气剂:

public class MainProjectsAppService : ApplicationService
{
    private readonly IDbContextProvider<DecentralizationDbContext> _dbContextProvider;
    private DecentralizationDbContext _ctx => _dbContextProvider.GetDbContext();

    public MainProjectsAppService(IDbContextProvider<DecentralizationDbContext> dbContextProvider)
    {
        _dbContextProvider = dbContextProvider;
    }
}

参考:aspnetboilerplate/aspnetboilerplate#4809

于 2020-02-02T16:00:02.687 回答