Skip to content

Instantly share code, notes, and snippets.

@jasonmitchell
Created December 17, 2012 21:11
Show Gist options
  • Save jasonmitchell/4322305 to your computer and use it in GitHub Desktop.
Save jasonmitchell/4322305 to your computer and use it in GitHub Desktop.
public class Customer
{
[Key]
public int ID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
public class EntityFrameworkRepository : IRepository
{
private readonly SiteDataContext dataContext;
public EntityFrameworkRepository(SiteDataContext dataContext)
{
this.dataContext = dataContext;
}
public void Save()
{
dataContext.SaveChanges();
}
public IQueryable<T> Query<T>(Expression<Func<T, bool>> filter = null) where T : class
{
IQueryable<T> query = dataContext.Set<T>();
if (filter != null)
query = query.Where(filter);
return query;
}
public T SingleOrDefault<T>(Expression<Func<T, bool>> predicate) where T : class
{
return dataContext.Set<T>().SingleOrDefault(predicate);
}
public void Insert<T>(T entity) where T : class
{
dataContext.Set<T>().Add(entity);
}
public void Update<T>(T entity) where T : class
{
DbEntityEntry entityEntry = dataContext.Entry(entity);
if(entityEntry.State == EntityState.Detached)
{
dataContext.Set<T>().Attach(entity);
entityEntry.State = EntityState.Modified;
}
}
public void Delete<T>(T entity) where T : class
{
dataContext.Set<T>().Remove(entity);
}
}
public interface IRepository
{
void Save();
IQueryable<T> Query<T>(Expression<Func<T, bool>> filter = null) where T : class;
T SingleOrDefault<T>(Expression<Func<T, bool>> predicate) where T : class;
void Insert<T>(T entity) where T : class;
void Update<T>(T entity) where T : class;
void Delete<T>(T entity) where T : class;
}
var customers = from c in repository.Query<Customer>()
where c.FirstName == "Jason"
select c;
var customer = repository.Query<Customer>(c => c.FirstName == "Jason");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment