-
-
Save anonymous/d0194b0cf0b29052f1b2 to your computer and use it in GitHub Desktop.
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
public class GenericRepository<T> : IRepository<T> where T : class | |
{ | |
public GenericRepository(DbContext context) | |
{ | |
if (context == null) | |
{ | |
throw new ArgumentException("An instance of DbContext is required to use this repository.", "context"); | |
} | |
this.Context = context; | |
this.DbSet = this.Context.Set<T>(); | |
} | |
protected IDbSet<T> DbSet { get; set; } | |
protected DbContext Context { get; set; } | |
public virtual IQueryable<T> All() | |
{ | |
return this.DbSet.AsQueryable(); | |
} | |
public virtual T GetById(object id) | |
{ | |
return this.DbSet.Find(id); | |
} | |
public virtual void Add(T entity) | |
{ | |
var entry = this.Context.Entry(entity); | |
if (entry.State != EntityState.Detached) | |
{ | |
entry.State = EntityState.Added; | |
} | |
else | |
{ | |
this.DbSet.Add(entity); | |
} | |
} | |
public virtual void Update(T entity) | |
{ | |
var entry = this.Context.Entry(entity); | |
if (entry.State == EntityState.Detached) | |
{ | |
this.DbSet.Attach(entity); | |
} | |
entry.State = EntityState.Modified; | |
} | |
public virtual void Delete(T entity) | |
{ | |
var entry = this.Context.Entry(entity); | |
if (entry.State != EntityState.Deleted) | |
{ | |
entry.State = EntityState.Deleted; | |
} | |
else | |
{ | |
this.DbSet.Attach(entity); | |
this.DbSet.Remove(entity); | |
} | |
} | |
public virtual void Delete(object id) | |
{ | |
var entity = this.GetById(id); | |
if (entity != null) | |
{ | |
this.Delete(entity); | |
} | |
} | |
public virtual T Attach(T entity) | |
{ | |
return this.Context.Set<T>().Attach(entity); | |
} | |
public virtual void Detach(T entity) | |
{ | |
var entry = this.Context.Entry(entity); | |
entry.State = EntityState.Detached; | |
} | |
public int SaveChanges() | |
{ | |
return this.Context.SaveChanges(); | |
} | |
public void Dispose() | |
{ | |
this.Context.Dispose(); | |
} | |
} |
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
public interface IRepository<T> : IDisposable where T : class | |
{ | |
IQueryable<T> All(); | |
T GetById(object id); | |
void Add(T entity); | |
void Update(T entity); | |
void Delete(T entity); | |
void Delete(object id); | |
T Attach(T entity); | |
void Detach(T entity); | |
int SaveChanges(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment