public virtual T FindById(object id) { using (var context = new ModernHisContext()) { return(context.Set <T>().Find(id)); } }
public IEnumerable <T> FindBySQL(string sql, params object[] sqlParams) { using (var context = new ModernHisContext()) { return(context.Database.SqlQuery <T>(sql, sqlParams).ToList()); } }
public void Delete(T obj) { using (var context = new ModernHisContext()) { context.Set <T>().Remove(obj); context.SaveChanges(); } }
public virtual IEnumerable <T> FindAll() { using (var context = new ModernHisContext()) { return(context.Set <T>() .Select(p => p) .ToList()); } }
public T Save(T obj) { using (var context = new ModernHisContext()) { context.Set <T>().Add(obj); context.SaveChanges(); return(obj); } }
public virtual IEnumerable <V> FindBySelect <V>(Func <T, V> selectExpression) { using (var context = new ModernHisContext()) { return(context.Set <T>() .Select(selectExpression) .ToList()); } }
public virtual IEnumerable <T> FindByLinq(Func <T, bool> expression) { using (var context = new ModernHisContext()) { return(context.Set <T>() .Where(expression) .Select(p => p) .ToList()); } }
public void DeleteById(object id) { using (var context = new ModernHisContext()) { var obj = context.Set <T>().Find(id); if (obj != null) { context.Set <T>().Remove(obj); context.SaveChanges(); } } }
/// <summary> /// EF的更新最好的办法就是先查询再修改,不然很麻烦 /// </summary> /// <param name="obj"></param> /// <param name="getPkHandler"></param> public void Update(T obj, Func <T, object> getPkHandler) { using (var context = new ModernHisContext()) { var key = getPkHandler.Invoke(obj); var oldObj = context.Set <T>().Find(key); if (oldObj != null) { ObjectRefletUtil.SetValue <T>(oldObj, obj); context.Entry <T>(oldObj).State = EntityState.Modified; context.SaveChanges(); } } }
public void DeleteByLinq(Func <T, bool> whereExpression) { using (var context = new ModernHisContext()) { var objs = context.Set <T>() .Where(whereExpression) .Select(p => p); foreach (var obj in objs) { context.Set <T>().Remove(obj); } context.SaveChanges(); } }
private void testTran() { //数据库上下文 using (var context = new ModernHisContext()) { //开启事务 using (var scope = context.Database.BeginTransaction()) { try { //添加一个famousePerson var famousePerson = new FamousPerson(); context.FamousPersons.Add(famousePerson); //添加一个historyEvent var historyEvent = new HistoryEvent(); context.HistoryEvents.Add(historyEvent); scope.Commit(); //正常完成就可以提交,famousePerson和historyEvent都会添加 } catch (Exception ex) { scope.Rollback(); //发生异常就回滚,famousePerson和historyEvent都不会添加 } } } //数据库上下文 using (var context = new ModernHisContext()) { //添加一个famousePerson var famousePerson = new FamousPerson(); context.FamousPersons.Add(famousePerson); //添加一个historyEvent var historyEvent = new HistoryEvent(); context.HistoryEvents.Add(historyEvent); context.SaveChanges(); //savechanges方法会将对数据库的多个封装为一个完整的事务 } }