Created
June 23, 2011 00:42
-
-
Save stirno/1041639 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
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