1

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?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Possible duplicate of [What goes into DbContextOptions when invoking a new DbContext?](https://stackoverflow.com/questions/38417051/what-goes-into-dbcontextoptions-when-invoking-a-new-dbcontext) – Igor Apr 15 '18 at 09:48

4 Answers4

3

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")`;
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Lakmal
  • 779
  • 1
  • 8
  • 16
1
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

Irakli Gabisonia
  • 806
  • 8
  • 19
0

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

ssmith
  • 8,092
  • 6
  • 52
  • 93
0

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);
}
Truc
  • 386
  • 4
  • 12