Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Repository, CreateObjectSet<T>() Method

Tags:

I was trying to implement a generic repository, and I have this right now:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Entity.Core.Objects;
using Web_API.Models;

namespace Web_API.DAL
{
    class GenericRepository<T> : IRepository<T> where T : class
    {
        private ApplicationDbContext entities = null;
        IObjectSet<T> _objectSet;

        public GenericRepository(ApplicationDbContext _entities)
        {
            entities = _entities;
            _objectSet = entities.CreateObjectSet<T>();
        }

        ...

I'm having trouble with this method call: entities.CreateObjectSet<T>(); It should be fine, however I get this error:

enter image description here

I have already added the System.Data.Entity to my project and at this point I don't know what else to do. I am following this tutorial http://www.codeproject.com/Articles/770156/Understanding-Repository-and-Unit-of-Work-Pattern. Does anyone know how to fix this issue?

like image 399
João Paiva Avatar asked May 15 '16 15:05

João Paiva


People also ask

What is generic repository pattern?

It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source.

What is the use of Unitofwork?

The unit of work class serves one purpose: to make sure that when you use multiple repositories, they share a single database context. That way, when a unit of work is complete you can call the SaveChanges method on that instance of the context and be assured that all related changes will be coordinated.


1 Answers

You will need to change your method to look like this:

public GenericRepository(ApplicationDbContext _entities)
{
    entities = _entities;
    _objectSet = entities.Set<T>(); //This line changed.
}

This should have the function that you desire. The .Set<T>() is the generic method that returns the DbSet of the type used.

UPDATE:

With the change in return type you will need to change your _objectSet type as well.

DbSet<T> _objectSet;
like image 58
Matt Rowland Avatar answered Sep 28 '22 03:09

Matt Rowland