Skip to content

Instantly share code, notes, and snippets.

@MarioBinder
Created January 4, 2015 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarioBinder/88c93cb6cbf4171b3942 to your computer and use it in GitHub Desktop.
Save MarioBinder/88c93cb6cbf4171b3942 to your computer and use it in GitHub Desktop.
EF CRUD
public static class Crud
{
public static int Save<T>(this T entity, ZeiterfassungsContext ctx) where T : class, ICrud
{
if (entity == null)
throw new ArgumentNullException("entity", "Die Entität darf nicht null sein");
return Exists(entity, "Id", ctx) ? Update(entity, ctx) : Insert(entity, ctx);
}
public static int Insert<T>(this T entity, ZeiterfassungsContext ctx) where T : class, ICrud
{
int result;
Add(entity, ctx, out result);
return result;
}
public static int Update<T>(this T entity, ZeiterfassungsContext ctx) where T : class, ICrud
{
int result;
Change(entity, ctx, out result);
return result;
}
public static IQueryable<T> Get<T>(Expression<Func<T, bool>> predicate, ZeiterfassungsContext ctx) where T : class, ICrud
{
return ctx.Set<T>().Where(predicate);
}
public static int Delete<T>(this T entity, ZeiterfassungsContext ctx) where T : class, ICrud
{
ctx.Set<T>().Remove(entity);
return ctx.SaveChanges();
}
private static void Add<T>(T entity, ZeiterfassungsContext ctx, out int result) where T : class, ICrud
{
using (var scope = new TransactionScope())
{
ctx.Set<T>().Add(entity);
ctx.SaveChanges();
result = (int)GetPropertyValue(entity, "Id");
scope.Complete();
}
}
private static void Change<T>(T entity, ZeiterfassungsContext ctx, out int result) where T : class, ICrud
{
var currentEntity = ctx.Set<T>().Find(GetPropertyValue(entity, "Id"));
ctx.Entry(currentEntity).CurrentValues.SetValues(entity);
using (var scope = new TransactionScope())
{
ctx.SaveChanges();
result = (int)GetPropertyValue(entity, "Id");
scope.Complete();
}
}
private static bool Exists<T>(T entity, string propertyname, ZeiterfassungsContext ctx) where T : class, ICrud
{
return ctx.Set<T>().Find(GetPropertyValue(entity, propertyname)) != null;
}
private static object GetPropertyValue<T>(T entity, string prop)
{
PropertyInfo info = entity.GetType().GetProperty(prop);
return info.GetValue(entity, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment