csharp EF CRUD
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 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);
}
}
以上是关于csharp EF CRUD的主要内容,如果未能解决你的问题,请参考以下文章