mahdi_elahitest
mahdi_elahitest

Reputation: 33

Initializing DBContext in Asp.Net Core

I want to use Repository & Unit Of Work in my project. But in ASP.NET MVC when we want use DBContext to use this code

MyDbContext db=new MyDbContext();

but in ASP.NET Core when write this code it want an argument because use this code in DbContext Class

public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

Error:
Error what is the problem?

Upvotes: 1

Views: 9897

Answers (4)

Lakmal
Lakmal

Reputation: 938

You can initilize your DB context like this:

var optionBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionBuilder.UseSqlServer("Server=localhost;...");
var context = new MyDbContext(optionBuilder.Options);

Previous code is configuring the options to the connection and then creating a MyDbContext using those options.

If you want to use a InMemoryDatabase for unit testing for example you can change it to this:

var optionBuilder = new DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase("testindDB")`;

Upvotes: 5

Truc
Truc

Reputation: 462

You can try it: In your class UnitOfWork

private MyDBContext _context;

public UnitOfWork(MyDBContext context)
{
      _context = context;
}

In your controller:

private UnitOfWork _unitOfWork;

public MoviesController(MyDBContext context)
{
      _unitOfWork = new UnitOfWork(context);
}

Upvotes: 0

ssmith
ssmith

Reputation: 8962

You shouldn't be instantiating the DbContext, you should be requesting it as a constructor argument to your repository. Then your IOC container will provide the DbContext at runtime. This ensures that you can use the same DbContext throughout a given ASP.NET web request, which will prevent a host of problems you're otherwise likely to encounter.

You can see an example of a generic repository here: http://deviq.com/repository-pattern/

You also typically don't need a separate Unit of Work in ASP.NET applications (but sometimes you do). This is because your requests should be very small and you should be able to do most of the work in a single controller or service, and then simply save through the repository. It's not that you never need UoW, but it's less necessary than in a thick client scenario (e.g. windows app or service).

Upvotes: 0

Irakli Gabisonia
Irakli Gabisonia

Reputation: 849

public MyDbContext(DbContextOptions<MyDbContext> options)

You have not empty constructor in your MyDbContext class, So you should do pass parameter DbContextOptions<MyDbContext> options in constructor.

For example you can see it -> link1

Upvotes: 1

Related Questions