0

I have a question related to the use of database contexts outside the controller, namely, how to call the database context in a regular class? To communicate with the database, I use: EF Core

I used options like this:

private readonly MSSQLContext _context;

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

Alternative

            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; }

and more tables...

2 Answers 2

1

You need to inject context using DI(dependency injection). I am showing you an example of repository pattern. You can search for "Repository pattern EF Core C# examples" will give you lots of examples or blogs to follow. Check here and here

Check out below example..

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();
         }
}

Startup.cs of MVC project

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);

        }
}
}
Sign up to request clarification or add additional context in comments.

Comments

1

Inject the context into whatever class you need to call into and register that class with the DI framework in your startup class.

For instance,

services.AddTransient<YourType>();

class YourType
{
    public YourType(YourDbContext context) { ... }
}

4 Comments

"Error CS7036 Missing argument corresponding to the required formal parameter "context" from "Bitrix24_API.Bitrix24_API (MSSQLContext)" " And how to overcome this? Maybe I'm asking stupid questions :(
@Shadow_VRN36 How are you instantiating your class? Via DI or with the new keyword?
You need to use proper constructor for your dBcontext into repository.
I have added a sample for repository pattern into MVC project using EF Core. I hope this helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.