Home > Enterprise >  Using DBContext in repository class
Using DBContext in repository class

Time:11-07

I want to use my DBcontext in my repository class, but I don't know how at the moment. I've tried looking at other questions, but they don't provide the answer needed specific for my case.

I'll start with my controller:

public class MovieController : ControllerBase
{
    IMovieService _movieService;
    public MovieController(IMovieService movieService)
    {
        _movieService = movieService;
    }

Service class:

public interface IMovieService
{
    Movie RetrieveMovie(long id);
    IEnumerable<Movie> RetrieveMovies();
}

public class MovieService : IMovieService
{
    IMovieRepository _movieRepository;

    public MovieService(IMovieRepository movieRepository)
    {
        _movieRepository = movieRepository;
    }

Repository class:

public interface IMovieRepository
{
    Movie GetMovieById(long id);
    IEnumerable<Movie> GetMovies();
}

public class MovieRepository : IMovieRepository
{
    private readonly MusicContext _db;
    public Movie GetMovieById(long id)
    {
        return _db.Movie.Find(id);
    }

DBContext:

public class MovieContext : DbContext
{
    public MovieContext(DbContextOptions<MovieContext> options)
        : base(options)
    {
    }

    public DbSet<Movie> Movies { get; set; }
}

And last my startup function:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MovieContext>(options =>                                
        options.UseSqlServer(Configuration.GetConnectionString("MovieContext")));
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "Movie.Api", Version = "v1" });
        });
    }

At the moment Visual studio warns me @ MusicContext _db that this field is never assigned to, which I get. How can I get this to work?

CodePudding user response:

you have to add a constructor to a MovieRepository and use DI

public class MovieRepository : IMovieRepository
{
    private readonly MovieContext _db;

    public MovieRepository (MovieContext db)
   {
            _db=db;
   }

    public Movie GetMovieById(long id)
    {
        return _db.Movie.Find(id);
    }
    .....
}
  • Related