using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Linq.Expressions; using EntityFramework.Extensions; using OpenAuth.Domain.Interface; using OpenAuth.Repository.Models; using Infrastructure; namespace OpenAuth.Repository { public class BaseRepository :IRepository where T :class { protected OpenAuthDBContext Context = new OpenAuthDBContext(); /// /// 根据过滤条件,获取记录 /// /// The exp. public IQueryable Find(Expression> exp = null) { return Filter(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) { Context.Set().Add(entity); Save(); } public void Update(T entity) { var entry = this.Context.Entry(entity); //todo:如果状态没有任何更改,会报错 entry.State = EntityState.Modified; Save(); } public void Delete(T entity) { Context.Set().Remove(entity); Save(); } public void Update(Expression> identityExp, T entity) { //TODO: 暂时有问题,EntityFramework.Extension的Update必须有new操作 // Context.Set().Where(exp).Update(u => entity); Context.Set().AddOrUpdate(identityExp, entity); Save(); } public void Delete(Expression> exp) { Context.Set().Where(exp).Delete(); } public void Save() { Context.SaveChanges(); } private IQueryable Filter(Expression> exp) { var dbSet = Context.Set().AsQueryable(); if (exp != null) dbSet = dbSet.Where(exp); return dbSet; } } }