【问题标题】:Objext of DBContext not getting initialized within a class in ASP.NET core using EntityFramework Core使用 EntityFramework Core 在 ASP.NET 核心的类中未初始化 DBContext 的对象
【发布时间】:2021-09-14 13:59:33
【问题描述】:

我已经在我的项目中初始化了 Dbcontext,现在我正在尝试使用其构造函数在一个类中使用 DBContext 对象获取数据,但它没有被初始化并且该对象具有空值。

{
    public SSIMContext(DbContextOptions<SSIMContext> DBdata) :
        base(DBdata)
    {
    }
    public DbSet<ScvCertificate> ScvCertificates { get; set; }
    public DbSet<ReconcileRequests> ReconcileRequests { get; set; }
    public DbSet<ResponseToDF> ResponseToDF { get; set; }
}

//在startup.cs中注册SSIMContext

        services.AddDbContextPool<SSIMContext>(
            data => data.UseSqlServer(Configuration.GetConnectionString("IdracDBConnection")));

//在控制器中为 dbcontext 获取数据按预期工作,但相同的方法在普通类中不起作用

    using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebCoreHSMAPI.Models;

namespace WebCoreHSMAPI.DataAccessLayer
{
    public class GetResponseMessages
    {
       public static SSIMContext _context;
      
        public GetResponseMessages(SSIMContext context)
        {
            _context = context;
        }

        public static List<ResponseToDF> GetResponseMessage(string MessageType,string ProcessingNode)
        {
            try
            {

                    List<ResponseToDF> ResponseToDF = _context.ResponseToDF.FromSqlRaw("UP_GET_RESPONSEDATA {0},{1}", MessageType, ProcessingNode).ToList();
                    return ResponseToDF;
                
             
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}

//这样调用方法:

 public static void GetMessages(string MessageType,string ProcessingNode)
    {
        try
        {
            List<ResponseToDF> response = GetResponseMessages.GetResponseMessage(MessageType, ProcessingNode);
        }
        catch (Exception ex)
        {

            throw;
        }
    }

对此的任何帮助将不胜感激..在此先感谢:)

【问题讨论】:

  • 如何实例化GetResponseMessages? (IMO 是用词不当。类是 do事物,因此它们应该有一个名词作为名称,而不是动词。它们的方法是动词。)跨度>
  • @Rena 按照你的建议对我不起作用,我会发布解决方案

标签: c# asp.net-core entity-framework-core dbcontext


【解决方案1】:

您很可能(或根本没有)通过依赖注入来实例化 GetResponseMessages 类。

您需要将其添加为服务。

分享您使用的代码,以便我们提供更多帮助。

我敢打赌,你直接使用静态方法

GetResponseMessages.GetResponseMessage(/*...*/)

您应该将签名更改为

public List<ResponseToDF> GetResponseMessage(string MessageType,string ProcessingNode)

并使用该类的实例。

【讨论】:

  • 我添加了调用方法的方式
【解决方案2】:

这是一个您可以关注的工作演示:

services.AddDbContext<SSIMContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("YourConnectionString")));

var optionsBuilder = new DbContextOptionsBuilder<SSIMContext>();
    optionsBuilder.UseSqlServer(Configuration.GetConnectionString("YourConnectionString"));

services.AddSingleton(new GetResponseMessages(optionsBuilder.Options));

数据库上下文:

public class SSIMContext: DbContext
{
    public SSIMContext(DbContextOptions<SSIMContext> options)
        : base(options)
    {
    }
 
    public DbSet<TestModel> Test{ get; set; }
}

【讨论】:

    【解决方案3】:

    在 program.cs 文件中我添加了这些行来配置 dbcontextfactory(标记为**)

        namespace SSIMToDFMessaging
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args).UseWindowsService()
                    .ConfigureServices((hostContext, services) =>
                    {
                        **string connectionString = hostContext.Configuration.GetSection("ConnectionStrings").GetSection("IdracDBConnection").Value;**
                        services.AddHostedService<SSIMToDFMessagingService>();
                        **services.AddDbContextFactory<SSIMContext>(options => options.UseSqlServer(connectionString))**;
    
                    });
        }
    }
    

    在服务中我以这种方式获取实例

     SSIMContext _context;
          public SSIMToDFMessagingService(ILogger<SSIMToDFMessagingService> logger, IDbContextFactory<SSIMContext> dbContextFactory, IConfiguration _config)
            {
                
                // _logger = logger;
                **_context = dbContextFactory.CreateDbContext();**
                // dbContextFactory1 = dbContextFactory;
                configuration = _config;
    
            }
    

    【讨论】:

      猜你喜欢
      • 2018-02-10
      • 1970-01-01
      • 2021-09-19
      • 2017-08-31
      • 2019-12-10
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      相关资源
      最近更新 更多