using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Linq; using System.Linq.Expressions; using CommonTool; using EntityFramework.Extensions; using YZXYH.Repository.Models; using YZXYH.Repository.Interface; namespace YZXYH.Repository { public class BaseRepository where T : class, new() { protected Yzxyh2017Context Context; internal DbSet DbSet; protected IUnitOfWork UnitOfWork; public BaseRepository(Yzxyh2017Context context) { Context = context; DbSet = context.Set(); UnitOfWork = new UnitOfWork(context); } /// /// 是否存在 /// /// 过滤条件 /// public bool IsExist(Expression> exp) { return Context.Set().Any(exp); } /// /// 过滤排序查询 /// /// 过滤条件(eg: u=>u.Id="1") /// 排序(eg: q=>q.OrderByDescending(u=>u.Name)) /// 外键 /// 对象集合 public IQueryable Get(Expression> exp = null, Func, IOrderedQueryable> orderBy = null, string includeProperties = "") { IQueryable dbSet = DbSet; if (exp != null) dbSet = DbSet.Where(exp); foreach (var includeProperty in includeProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { dbSet = dbSet.Include(includeProperty); } if (orderBy != null) { return orderBy(dbSet); } return dbSet; } /// /// 分页排序记录 /// /// The pageindex. /// The pagesize. /// 排序(eg: q=>q.OrderByDescending(u=>u.Name)) /// 过滤条件(eg: u=>u.Id="1") /// 外键 public IQueryable Get(int pageindex, int pagesize, Func, IOrderedQueryable> orderBy = null, Expression> exp = null, string includeProperties = "") { if (pageindex < 1) pageindex = 1; return Get(exp, orderBy, includeProperties).Skip(pagesize * (pageindex - 1)).Take(pagesize); } /// /// 查找单个 /// public T GetSingle(Expression> exp) { return DbSet.AsNoTracking().FirstOrDefault(exp); } /// /// 根据Id获取数据 /// /// /// public T GetById(string id) { return DbSet.Find(id); } /// /// 根据过滤条件获取记录数 /// public int GetCount(Expression> exp = null) { return Get(exp).Count(); } /// /// 普通插入 /// /// public void Insert(T t) { DbSet.Add(t); } /// /// 没有主键Id的插入 /// /// public void InsertNoId(T t) { var propertyInfo = t.GetType().GetProperty("Id"); if (propertyInfo != null) propertyInfo.SetValue(t, Guid.NewGuid().ToString("N")); DbSet.Add(t); } /// /// 批量插入 /// /// The entities. public void BatchInsert(T[] ts) { foreach (var t in ts) { var propertyInfo = t.GetType().GetProperty("Id"); if (propertyInfo != null) propertyInfo.SetValue(t, Guid.NewGuid().ToString("N")); } DbSet.AddRange(ts); } /// /// 删除记录 /// /// public void Delete(T t) { DbSet.Attach(t); DbSet.Remove(t); } /// /// 删除记录 /// /// 过滤条件 public virtual void Delete(Expression> exp) { DbSet.Where(exp).Delete(); } /// ///根据Id删除 /// /// public void DeleteById(string id) { Delete(GetById(id)); } /// /// 更新 /// /// public void Update(T t) { DbSet.Attach(t); Context.Entry(t).State = EntityState.Modified; } /// /// 实现按需要只更新部分更新 /// 如:Update(u =>u.Id==1,u =>new User{Name="ok"}); /// /// The where. /// The entity. public void Update(Expression> where, Expression> t) { Context.Set().Where(where).Update(t); } /// /// 按指定id更新实体,会更新整个实体 /// /// The identity exp. /// The entity. public void Update(Expression> identityExp, T t) { DbSet.AddOrUpdate(identityExp, t); } /// /// 查询记录条数 /// /// 参数 “表名 | 条件语句 , 表名 | 条件语句” /// (多个查询以 , 分隔,表名与条件语句以 | 分隔) /// public string[] GetCounts(string[] queryStrs) { List counts = new List { "true" }; foreach (var queryStr in queryStrs) { string[] strs = queryStr.Split('|'); if (strs.Length != 2) { counts.Clear(); counts.Add("参数有误,请检查!" + strs[0]); return counts.ToArray(); } var tableName = strs[0]; var whereStr = strs[1]; try { var sqlStr = $"SELECT Count(*) FROM {tableName} WHERE {whereStr} "; var count = Context.Database.SqlQuery(sqlStr).First().ToString(); //var count = db.Database.SqlQuery("SELECT Count(*) FROM @p0 WHERE @p1", new SqlParameter("@p0", tableName), new SqlParameter("@p1", whereStr)).First().ToString(); counts.Add(count); } catch { counts.Clear(); counts.Add("参数有误!请检查! " + tableName + " || " + whereStr); return counts.ToArray(); } } return counts.ToArray(); } public bool Save() { try { Context.SaveChanges(); return true; } catch(DbEntityValidationException e) { LogHelper.Error(e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); return false; } } } }