EntityFramework Repository Pattern

Viewed 479

I've been having a problem with my code. I've started learning Entityframework, as a resorce i've used Microsoft Virtual Academy website, they have a short intro for Entity Framework and asp.net. They have created this repository generic class that takes poco classes.

public class Repository<T> where T : class
{
    private BlogDataContext context = null;
    protected DbSet<T> DbSet { get; set; }

    public Repository()
    {
        this.context = new BlogDataContext();
        DbSet = context.Set<T>();
    }

    public List<T> getAll()
    {
        return DbSet.ToList();
    }

    public T Get(int id)
    {
        return DbSet.Find(id);
    }

    public void Add(T entity)
    {
        DbSet.Add(entity);
    }

    public void Update(T entity)
    {
        context.Entry<T>(entity).State = EntityState.Modified;
    }

    public void Delete(int id)
    {
        DbSet.Remove(DbSet.Find(id));
    }

    public void SaveChanges()
    {
        context.SaveChanges();
    }
}

Problem appears when you need to edit data in database using ASP.NET Controls, Up until now I've manually bound data to controls and updated by finding the data with Get(int Id) and then updating. Recently I found out that the process can be automated with ObjectDataSource control but update method casts an error

Attaching an entity of type 'CarDealership.DataLayer.UsersExtended' failed because another entity of the same type already has the same primary key value.

UsersExtended is a poco class.

1 Answers
Related