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?

1

4 Answers 4

5

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")`;
Sign up to request clarification or add additional context in comments.

1 Comment

I have explained the code and other options in detail.
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

Comments

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

1 Comment

how would you go about initilizing a DBcontext for UnitTesting or other kind of apps that are not ASP.NET ?
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);
}

Comments

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.