/// <summary> /// 增加与修改方法 /// </summary> /// <param name="list"></param> /// <param name="selectKey"></param> /// <param name="updateKey"></param> /// <param name="defDate"></param> /// <returns></returns> public async Task <int> AddUpdateAsync(List <T> list, string[] selectKey, string[] updateKey, string[] defDate) { using (DafujianContext db = new DafujianContext()) { try { foreach (var current in list) { var t = await db.Set <T>().Where(EfUtils.And <T>(selectKey, current)).FirstOrDefaultAsync <T>(); if (t == null) { foreach (var def in defDate) { current.GetType().GetProperty(def).SetValue(current, DateTime.Now, null); } current.GetType().GetProperty("IsDelete").SetValue(current, 0, null); db.Set <T>().Add(current); } else { foreach (var k in updateKey) { if (k.Equals("UpdateTime")) { t.GetType().GetProperty(k).SetValue(t, DateTime.Now, null); } else { var value = current.GetType().GetProperty(k).GetValue(current, null); t.GetType().GetProperty(k).SetValue(t, value, null); } } db.Set <T>().Attach(t); db.Entry <T>(t).State = EntityState.Modified; } } return(await db.SaveChangesAsync()); } catch (Exception ex) { var msg = string.Concat(new object[] { "Message:", ex.Message, "。 Source:", ex.Source, "。 TargetSite:", ex.TargetSite, "。 InnerException:", ex.InnerException }); Error.WriteLog("Repository-AddUpdateAsync-01", msg); return(-22); } } }
public async Task <T> GetAsync(Expression <Func <T, bool> > predicate) { using (DafujianContext db = new DafujianContext()) { if (predicate == null) { return(null); } return(await db.Set <T>().Where(predicate).FirstOrDefaultAsync <T>()); } }
/// <summary> /// 业务删除 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task <int> DeleteVirtualAsync(Guid[] ids, string idKey) { using (DafujianContext db = new DafujianContext()) { try { foreach (var id in ids) { var model = await db.Set <T>().Where(EfUtils.AndByGuid <T>(idKey, id)).FirstOrDefaultAsync <T>(); if (model == null) { continue; } model.GetType().GetProperty("UpdateTime").SetValue(model, DateTime.Now, null); model.GetType().GetProperty("IsDelete").SetValue(model, 99, null); db.Set <T>().Attach(model); db.Entry <T>(model).State = EntityState.Modified; } return(await db.SaveChangesAsync()); } catch (Exception ex) { var msg = string.Concat(new object[] { "Message:", ex.Message, "。 Source:", ex.Source, "。 TargetSite:", ex.TargetSite, "。 InnerException:", ex.InnerException }); Error.WriteLog("Repository-DeleteVirtualAsync-01", msg); return(-22); } } }