Created
November 14, 2013 04:24
-
-
Save dasjestyr/7461327 to your computer and use it in GitHub Desktop.
Generic Repository example. Can be used as a single repository that will work for every entity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Data.Entity; | |
using System.Linq; | |
namespace mycompany.employee_manager.Core.Data.Repository | |
{ | |
public class GenericRepository<TEntity> | |
where TEntity : class | |
{ | |
internal ProvausioEmployeeManagerContext Context; | |
internal DbSet<TEntity> DbSet; | |
public GenericRepository() : this(new MyApplicationContext()) { } | |
public GenericRepository(MyApplicationContext context) | |
{ | |
Context = context; | |
DbSet = context.Set<TEntity>(); | |
} | |
public virtual IEnumerable<TEntity> Get() | |
{ | |
IQueryable<TEntity> query = DbSet; | |
return query.ToList(); | |
} | |
public virtual TEntity GetById(object id) | |
{ | |
return DbSet.Find(id); | |
} | |
public virtual void Insert(TEntity entity) | |
{ | |
DbSet.Add(entity); | |
} | |
public virtual void Delete(object id) | |
{ | |
var toDelete = DbSet.Find(id); | |
Delete(toDelete); | |
} | |
public virtual void Delete(TEntity entity) | |
{ | |
if (Context.Entry(entity).State == EntityState.Detached) | |
{ | |
DbSet.Attach(entity); | |
} | |
DbSet.Remove(entity); | |
} | |
public virtual void Update(TEntity entity) | |
{ | |
DbSet.Attach(entity); | |
Context.Entry(entity).State = EntityState.Modified; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment