【问题标题】:C# Asp net core How to call database context outside of controllersC# Asp net core 如何在控制器之外调用数据库上下文
【发布时间】:2021-10-29 07:47:25
【问题描述】:

我有一个关于在控制器外使用数据库上下文的问题,即如何在常规类中调用数据库上下文? 为了与数据库通信,我使用:EF Core

我使用了这样的选项:

private readonly MSSQLContext _context;

    public BookingController(MSSQLContext context)
    {
        _context = context;
    }

另类

            using (MSSQLContext context=new MSSQLContext())
        {
            context.get_Users.ToList();
        }

Startup.cs

      services.AddDbContext<MSSQLContext>(options =>
            options.UseSqlServer(connection));

MSSQLContext.cs

        public MSSQLContext()
    {
    }

    public MSSQLContext(DbContextOptions<MSSQLContext> options)
        : base(options)
    {

    }
    public DbSet<VIVT_Core_Aud.Models.Core.Logger_Model> Logger_Models { get; set; }

还有更多表格...

【问题讨论】:

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


    【解决方案1】:

    将上下文注入到您需要调用的任何类中,并将该类注册到启动类中的 DI 框架中。

    例如,

    services.AddTransient<YourType>();
    
    class YourType
    {
        public YourType(YourDbContext context) { ... }
    }
    

    【讨论】:

    • “错误 CS7036 缺少与来自“Bitrix24_API.Bitrix24_API (MSSQLContext)”的所需形式参数“context”相对应的参数“以及如何克服这个问题?也许我在问愚蠢的问题:(
    • @Shadow_VRN36 你是如何实例化你的类的?通过 DI 还是使用 new 关键字?
    • 您需要使用适当的构造函数将您的 dBcontext 放入存储库。
    • 我已使用 EF Core 将存储库模式示例添加到 MVC 项目中。希望对您有所帮助。
    【解决方案2】:

    您需要使用 DI(依赖注入)来注入上下文。我正在向您展示存储库模式的示例。您可以搜索“存储库模式 EF Core C# 示例”将为您提供大量示例或博客供您参考。 Check herehere

    看看下面的例子..

    MyRepository.cs

    namespace MyApp.Data.Services
    {
        public class MyRepository: IMyRepository, IDisposable
        {
            private MyAppContext _context;
            private readonly ILogger<MyRepository> _logger;
    
            public MyRepository(MyAppContext context, ILogger<MyRepository> logger)
            {
                _context = context ?? throw new ArgumentNullException(nameof(context));
                _logger = logger;
            }
    
            public IEnumerable<MyTable> GetMyTableData()
            {
              return _context.MyTable.ToList();
             }
    }
    }
    

    IMyRepository.cs

    namespace MyApp.Data.Services
    {
        public interface IMyRepository
            {
               //Interface implementation
                IEnumerable<MyTable> GetMyTableData();
             }
    }
    

    MVC项目的Startup.cs

    services.AddDbContext<MyAppContext>(options =>
                            options.UseSqlServer(Configuration.GetConnectionString("AppDbConnString")));            
    
    //Scope of repository should be based on your project used, I recommend to check lifetime & scope based your project needs.     
    services.AddScoped<IMyRepository, MyRepository>();
               
    

    Mycontroller.cs

    using MyApp.Data.Services;
    
    namespace MyApp.Controllers
    {
        
        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly IMyRepository _myRepository;
    
    public HomeController(ILogger<HomeController> logger, IMyRepository myRepository)
            {
                _logger = logger;
                _myRepository = myRepository ??
                throw new ArgumentNullException(nameof(myRepository));                
                
            }
    
            public IActionResult Index()
            {
                return View();
            }
    public IActionResult GetAllData()
            {
                var result =  _myRepository.GetMyTableData();
                return Json(result);
    
            }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2018-04-18
      • 2020-08-26
      相关资源
      最近更新 更多