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:
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?
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With