using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Linq; using System.Linq.Expressions; using EntityFramework.Extensions; using Infrastructure; using OpenAuth.Repository.Interface; namespace OpenAuth.Repository { public class BaseRepository :IRepository where T :Domain.Entity { protected OpenAuthDBContext Context = new OpenAuthDBContext(); /// /// 根据过滤条件,获取记录 /// /// The exp. public IQueryable Find(Expression> exp = null) { return Filter(exp); } public bool IsExist(Expression> exp) { return Context.Set().Any(exp); } /// /// 查找单个,且不被上下文所跟踪 /// public T FindSingle(Expression> exp) { return Context.Set().AsNoTracking().FirstOrDefault(exp); } /// /// 得到分页记录 /// /// The pageindex. /// The pagesize. /// 排序,格式如:"Id"/"Id descending" public IQueryable Find(int pageindex, int pagesize, string orderby = "", Expression> exp = null) { if (pageindex < 1) pageindex = 1; if (string.IsNullOrEmpty(orderby)) orderby = "Id descending"; return Filter(exp).OrderBy(orderby).Skip(pagesize * (pageindex - 1)).Take(pagesize); } /// /// 根据过滤条件获取记录数 /// public int GetCount(Expression> exp = null) { return Filter(exp).Count(); } public void Add(T entity) { if (string.IsNullOrEmpty(entity.Id)) { entity.Id = Guid.NewGuid().ToString(); } Context.Set().Add(entity); Save(); } /// /// 批量添加 /// /// The entities. public void BatchAdd(T[] entities) { foreach (var entity in entities) { entity.Id = Guid.NewGuid().ToString(); } Context.Set().AddRange(entities); Save(); } public void Update(T entity) { var entry = this.Context.Entry(entity); entry.State = EntityState.Modified; //如果数据没有发生变化 if (!this.Context.ChangeTracker.HasChanges()) { return; } Save(); } public void Delete(T entity) { Context.Set().Remove(entity); Save(); } /// /// 按指定id更新实体,会更新整个实体 /// /// The identity exp. /// The entity. public void Update(Expression> identityExp, T entity) { Context.Set().AddOrUpdate(identityExp, entity); Save(); } /// /// 实现按需要只更新部分更新 /// 如:Update(u =>u.Id==1,u =>new User{Name="ok"}); /// /// The where. /// The entity. public void Update(Expression> where, Expression> entity) { Context.Set().Where(where).Update(entity); } public virtual void Delete(Expression> exp) { Context.Set().Where(exp).Delete(); } public void Save() { try { Context.SaveChanges(); } catch (DbEntityValidationException e) { throw new Exception(e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); } } private IQueryable Filter(Expression> exp) { var dbSet = Context.Set().AsQueryable(); if (exp != null) dbSet = dbSet.Where(exp); return dbSet; } public int ExecuteSql(string sql) { return Context.Database.ExecuteSqlCommand(sql); } } }