Skip to content

Instantly share code, notes, and snippets.

@stirno
Created June 23, 2011 00:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stirno/1041639 to your computer and use it in GitHub Desktop.
Save stirno/1041639 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTNX.DNS.DataAccess.Repositories
{
public class RepositoryBase<T> where T : ModelBase
{
public RepositoryBase()
{
this.DbContext = new DbContext();
}
public virtual DbContext DbContext { get; set; }
public virtual T Get(int id)
{
return DbContext.Set<T>().Find(id);
}
public virtual T Save(T item)
{
if (item.Id == 0)
{
DbContext.Set<T>().Add(item);
}
else
{
DbContext.Entry(DbContext.Set<T>().Find(item.Id)).CurrentValues.SetValues(item);
}
DbContext.SaveChanges();
return item;
}
public virtual List<T> GetAll()
{
return DbContext.Set<T>().ToList();
}
public virtual List<T> Save(List<T> items)
{
foreach (var item in items)
{
if (item.Id == 0)
{
DbContext.Set<T>().Add(item);
}
else
{
DbContext.Entry(DbContext.Set<T>().Find(item.Id)).CurrentValues.SetValues(item);
}
}
DbContext.SaveChanges();
return items;
}
public virtual bool Delete(T item)
{
T record = DbContext.Set<T>().Find(item.Id);
if (record != null)
{
DbContext.Set<T>().Remove(record);
DbContext.SaveChanges();
return true;
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment