本文章为ASP.net MVC 构建layui管理后台,第一篇。

使用EF+ado.net 实体数据模型模式进行底层的数据库连接。

在项目添加一个类库Model

在类库Model上添加一个ado.net 实体数据模型

添加成功之后,效果如下

按照以上的步骤,已经完成了,对应数据库的连接,关联,下面我们来定义数据库的存储。

在Model类库下新建EFDbContext类,用于连接数据库

 /// <summary>
/// 连接数据库
/// </summary>
/// <returns></returns>
public static ZWSDBEntities GetDbContext()
{
ZWSDBEntities dbContext = CallContext.GetData("ZWSDBEntities") as ZWSDBEntities;
if (dbContext == null)
{
dbContext = new ZWSDBEntities();
CallContext.SetData("ZWSDBEntities", dbContext);
}
return dbContext;
}

其中ZWSDBEntities是每个人的可能不一样,可以在下图中找

接下来定义两个接口IBaseEntityDAL,IBaseEntityService

 /// <summary>
/// 封装定义数据操作接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IBaseEntityDAL<T> where T : class
{
//! 检查是否存在持久实体对象
bool HasInstance(Expression<Func<T, bool>> where);
bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where); //! 提取单个对象的方法
T GetByIntID(int id);
T GetByStringID(string oid);
T GetByGuid(Guid oid);
T GetByLambda(Expression<Func<T, bool>> where); //! 根据 id ,提取实例,如果没有,创建一个新的实例,并执行持久化
T GetOrCreatePersistence(Guid id);
//! 根据 id ,提取实例,如果没有,创建一个新的实例,但不执行持久化
T GetOrCreateNotPersistence(Guid id); //! 添加对象的方法
void Add(T bo);
void AddOrUpdate(T bo, bool isForNewObject, ref int returnPoint); //! 删除对象的方法
void Delete(T bo);
void DeleteRelevenceObject<T2>(T2 relevanceBo);
void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where); //! 更新对象的方法
void Update(T bo); //! 提取对象集合的方法
IQueryable<T> GetAll();
IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order);
IQueryable<T> GetMany(Expression<Func<T, bool>> where);
IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val);
IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order);
IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
//IQueryable<T> GetDataPaging(DataTableModel dataTableModel, ref int dataAmount, string orderProperty, Expression<Func<T, bool>> where = null);
IQueryable<T> GetAllCommonWay(
ref int pageAmount,
ref int boAmount,
Expression<Func<T, bool>> where = null,
Expression<Func<T, bool>> order = null,
bool? isDesc = null,
int? page = null,
int? pageSize = null); //! 数据处理约束管理方法
bool CanAdd(Expression<Func<T, bool>> where); //! 用于处理一些附加对象的方法
T2 GetRelevanceObject<T2>(Guid id);
T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where);
T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString); IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where);
IQueryable<T2> GetRelevanceObjects<T2>(
Expression<Func<T2, bool>> where = null,
Expression<Func<T2, bool>> order = null,
bool? isDesc = null); void AddRelevanceObject<T2>(T2 relevanceBo);
void UpdateRelevanceObject<T2>(T2 relevanceBo);
}
/// <summary>
/// 封装定义数据操作接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IBaseEntityService<T> where T : class
{
/// <summary>
/// 检查是否存在持久实体对象
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
bool HasInstance(Expression<Func<T, bool>> where);
bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where); T GetByIntID(int id);
/// <summary>
/// 提取单个对象的方法(ID)
/// </summary>
/// <param name="oid">ID</param>
/// <returns></returns>
T GetByStringID(string oid);
/// <summary>
///提取单个对象的方法(GID)
/// </summary>
/// <param name="oid"></param>
/// <returns></returns>
T GetByGuid(Guid oid);
T GetByLambda(Expression<Func<T, bool>> where); //! 根据 id ,提取实例,如果没有,创建一个新的实例,并执行持久化
T GetOrCreatePersistence(Guid id);
//! 根据 id ,提取实例,如果没有,创建一个新的实例,但不执行持久化
T GetOrCreateNotPersistence(Guid id); //! 添加对象的方法
void Add(T bo);
void AddOrUpdate(T bo, bool isForNewObject, params Expression<Func<T, object>>[] updatedProperties); //! 删除对象的方法
void Delete(T bo); void DeleteRelevenceObject<T2>(T2 relevanceBo);
void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where); //! 更新对象的方法
void Update(T bo); void Update(T entity, params Expression<Func<T, object>>[] updatedProperties); //! 提取对象集合的方法
IQueryable<T> GetAll();
IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order);
IQueryable<T> GetMany(Expression<Func<T, bool>> where);
IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val);
IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order); //! 按照分页方式提取对象集合的方法
IQueryable<T> GetAllOrderedPaged(string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc); //IQueryable<T> GetDataPaging(GridPager page, ref int dataAmount, Expression<Func<T, bool>> where = null);
IQueryable<T> GetManyOrderedPaged<Tkey>(Expression<Func<T, bool>> where, Expression<Func<T, Tkey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
IQueryable<T> GetManyOrderedByProertyNamePaged(Expression<Func<T, bool>> where, string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
IQueryable<T> GetAllCommonWay(
ref int pageAmount,
ref int boAmount,
Expression<Func<T, bool>> where = null,
Expression<Func<T, bool>> order = null,
bool? isDesc = null,
int? page = null,
int? pageSize = null); //! 数据处理约束管理方法
bool CanAdd(Expression<Func<T, bool>> where); //! 用于处理一些附加对象的方法
T2 GetRelevanceObject<T2>(Guid id);
T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where);
T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString); IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where);
IQueryable<T2> GetRelevanceObjects<T2>(
Expression<Func<T2, bool>> where = null,
Expression<Func<T2, bool>> order = null,
bool? isDesc = null); IQueryable<T2> GetManyRelevanceObjectsOrderedByProertyNamePaged<T2>(Expression<Func<T2, bool>> where, string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc); void AddRelevanceObject<T2>(T2 relevanceBo);
void UpdateRelevanceObject<T2>(T2 relevanceBo);
}

两个操作类,BaseEntityDAL,BaseEntityService

 /// <summary>
/// 基于 EF CodeFirst 独立的针对 IBaseEntityService 方法的实现,其实际实现时通过继承的方式处理
///
/// 实现基础操作方法的基类
/// </summary>
public abstract class BaseEntityDAL<T> where T : class
{
protected readonly DbContext _Context;
protected readonly IDbSet<T> _DbSet; public BaseEntityDAL(DbContext context)
{
this._Context = context;
_DbSet = _Context.Set<T>();
} /// <summary>
/// 根据条件检查数据是否已存在
/// </summary>
/// <param name="where">Lamda表达式</param>
/// <returns>true:为不存在</returns>
public bool HasInstance(Expression<Func<T, bool>> where)
{
if (_DbSet.Where(where).FirstOrDefault() == null)
return true;
else
return false;
} public bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>; ;
if (dbSet.Where(where).FirstOrDefault() != null)
return true;
else
return false;
}
public T GetByStringID(string oid)
{
return _DbSet.Find(oid);
} public T GetByGuid(Guid oid)
{
return _DbSet.Find(oid);
} /// <summary>
/// 根据Lambda表达式获取一条数据
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public T GetByLambda(Expression<Func<T, bool>> where)
{
try
{
return _DbSet.Where(where).FirstOrDefault<T>();
}
catch (Exception e)
{
return null;
}
} //根据Guid获取一条数据,如果该数据不存在将创建一条数据,然后返回
public T GetOrCreatePersistence(Guid id)
{
var fObject = this.GetByGuid(id);
if (fObject != null)
return fObject;
else
{
fObject = Activator.CreateInstance<T>();
this.Add(fObject);
return fObject;
}
} public T GetOrCreateNotPersistence(Guid id)
{
var fObject = this.GetByGuid(id);
if (fObject != null)
return fObject;
else
{
fObject = Activator.CreateInstance<T>();
return fObject;
}
} public void Add(T bo)
{
_DbSet.Add(bo);
_Context.SaveChanges();
}
public void DelayedAdd(T bo)
{
_DbSet.Add(bo);
}
public int AllSaveChanges()
{
return _Context.SaveChanges(); }
public void AddOrUpdate(T bo, bool isForNewObject, ref int returnPoint)
{
if (isForNewObject)
{
this.Add(bo);
returnPoint = ;
}
else
{
this.Update(bo);
}
}
/// <summary>
/// 物理删除
/// </summary>
/// <param name="bo"></param>
public void DeleteEntity(T bo)
{
_DbSet.Remove(bo);
_Context.SaveChanges();
}
/// <summary>
/// 物理删除
/// </summary>
/// <param name="bo"></param>
public void DeleteByIds(params object[] ids)
{
if (ids != null)
{
string strIds = string.Join(",", ids);
_Context.Database.ExecuteSqlCommand(string.Format("delete {0} where ID in ('{1}') ", typeof(T).Name, strIds));
}
}
/// <summary>
/// 逻辑删除(使用时确保表中 含有用于标记逻辑删除的字段 IsDelete)
/// </summary>
/// <param name="bo"></param>
public void Delete(T bo)
{
PropertyInfo[] properties = typeof(T).GetProperties();
for (int i = properties.Length; i > ; i--)
{
string fn = properties[i - ].Name;
PropertyInfo pinfo = typeof(T).GetProperty(fn);
if ("IsDelete" == fn)
{
pinfo.SetValue(bo, true, null);
break;
}
}
_DbSet.Attach(bo);
_Context.Entry(bo).State = EntityState.Modified;
_Context.SaveChanges();
}
public void DeleteRelevenceObject<T2>(T2 relevanceBo)
{
var dbSet = _Context.Set(typeof(T2));
dbSet.Remove(relevanceBo);
_Context.SaveChanges();
} public void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2)); var tempCollection = dbSet as IQueryable<T2>;
foreach (var item in tempCollection.Where(where))
dbSet.Remove(item); _Context.SaveChanges();
} public void Update(T bo)
{
_DbSet.Attach(bo);
_Context.Entry(bo).State = EntityState.Modified;
_Context.SaveChanges();
} public IQueryable<T> GetAll()
{
return _DbSet as IQueryable<T>;
} //获取所有数据,根据条件排序
public IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order)
{
return _DbSet.OrderBy(order);
} public IQueryable<T> GetMany(Expression<Func<T, bool>> where)
{
return _DbSet.Where(where) as IQueryable<T>;
} public IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val)
{
//var queryBuilder = CustomLinq.Func((selector, val) =>
// from c in _DbSet.ToExpandable()
// where selector.Expand(c).IndexOf(val) != -1
// select c);
return _DbSet as IQueryable<T>;
} public IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order)
{
return _DbSet.Where(where).OrderBy(order);
} /// <summary>
/// 分页获取数据
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="dataTableModel">表格参数</param>
/// <param name="dataAmount">总条数</param>
/// <param name="orderProperty">要排序的对象名称</param>
/// <param name="where">搜索条件</param>
/// <returns></returns>
//public IQueryable<T> GetDataPaging(DataTableModel dataTableModel, ref int dataAmount, string orderProperty, Expression<Func<T, bool>> where = null)
//{
// var searchResult = _DbSet as IQueryable<T>;
// if (where != null)
// searchResult = searchResult.Where(where); // dataAmount = searchResult.Count();
// var isDesc = dataTableModel.OrderDir == "desc";
// searchResult = searchResult.OrderBy(orderProperty, isDesc).Skip(dataTableModel.Start).Take(dataTableModel.Length);
// return searchResult;
//} public IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
{
var searchResult = _DbSet as IQueryable<T>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ;
return searchResult.OrderBy(order).Skip((page - ) * pageSize).Take(pageSize);
}
public IQueryable<T> GetAllCommonWay(
ref int pageAmount,
ref int boAmount,
Expression<Func<T, bool>> where = null,
Expression<Func<T, bool>> order = null,
bool? isDesc = null,
int? page = null,
int? pageSize = null)
{
pageAmount = ;
boAmount = ;
var searchResult = _DbSet as IQueryable<T>; if (where != null && order != null)
{
searchResult = searchResult.Where(where);
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
else
{
if (where != null)
{
searchResult = searchResult.Where(where);
}
else
{
if (order != null)
{
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
}
} boAmount = searchResult.Count();
if (pageAmount == -)
{
pageAmount = -;
} if (page != null)
{
var p = (int)page;
var ps = (int)pageSize;
pageAmount = searchResult.Count() / ps;
searchResult = searchResult.Skip((p - ) * ps).Take(ps);
} return searchResult;
} public bool CanAdd(Expression<Func<T, bool>> where)
{
var count = _DbSet.Where(where).Count();
if (count > )
return false;
else
return true;
} public T2 GetRelevanceObject<T2>(Guid id)
{
var dbSet = _Context.Set(typeof(T2));
return (T2)dbSet.Find(id);
} public T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString)
{
var id = _Context.Database.SqlQuery<Guid>(SqlQureyString).FirstOrDefault();
if (id != null)
{
return GetRelevanceObject<T2>(id);
}
else
return default(T2);
} public T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>;
return (T2)dbSet.Where(where).FirstOrDefault();
} public IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2));
var searchResult = dbSet as IQueryable<T2>; return searchResult.Where(where);
} public IQueryable<T2> GetRelevanceObjects<T2>(
Expression<Func<T2, bool>> where = null,
Expression<Func<T2, bool>> order = null,
bool? isDesc = null)
{
var dbSet = _Context.Set(typeof(T2));
var searchResult = dbSet as IQueryable<T2>;
if (where != null && order != null)
{
searchResult = searchResult.Where(where);
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
else
{
if (where != null)
{
searchResult = searchResult.Where(where);
}
else
{
if (order != null)
{
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
}
} return searchResult;
} public void AddRelevanceObject<T2>(T2 relevanceBo)
{
var dbSet = _Context.Set(typeof(T2));
dbSet.Add(relevanceBo);
_Context.SaveChanges();
} public void UpdateRelevanceObject<T2>(T2 relevanceBo)
{
var tempBo = Activator.CreateInstance(typeof(T2));
tempBo = relevanceBo;
var dbSet = _Context.Set(typeof(T2));
dbSet.Attach(tempBo);
_Context.Entry(tempBo).State = EntityState.Modified;
_Context.SaveChanges();
} ///// <summary>
///// 从缓存中获取所有数据
///// </summary>
///// <returns></returns>
//public ICollection<T> GetAllByCache()
//{
// var key = typeof(T).Name + "List";
// var obj = this.GetByCache(key);
// if (obj == null)
// {
// obj = this.GetAll().ToList();
// this.SetInCache(key, obj);
// }
// return obj as ICollection<T>;
//}
///// <summary>
///// 从缓存中获取单个实体
///// </summary>
///// <param name="id"></param>
///// <returns></returns>
//public T GetByCache(Guid id)
//{
// var key = id.ToString();
// var obj = this.GetByCache(key);
// if (obj == null)
// {
// obj = this.GetByGuid(id);
// this.SetInCache(key, obj);
// }
// return obj as T;
//} ///// <summary>
///// 移除缓存中的数据(集合)
///// </summary>
//public void RemoveAllCache()
//{
// var key = typeof(T).Name + "List";
// this.RemoveCache(key);
//}
///// <summary>
///// 移除缓存中的数据(单个实体)
///// </summary>
///// <param name="id"></param>
//public void RemoveCache(Guid id)
//{
// var key = id.ToString();
// this.RemoveCache(key);
//}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
//public void SetInCache(string key, object val)
//{
// CacheHelper.Set(key, val);
//}
///// <summary>
///// 从缓存中获取数据
///// </summary>
///// <param name="key"></param>
///// <returns></returns>
//public object GetByCache(string key)
//{
// return CacheHelper.Get(key);
//}
///// <summary>
///// 从缓存中移除数据
///// </summary>
///// <param name="key"></param>
//public void RemoveCache(string key)
//{
// CacheHelper.Remove(key);
//}
}
 /// <summary>
/// 基于 EF CodeFirst 独立的针对 IBaseEntityService 方法的实现,其实际实现时通过继承的方式处理
/// </summary>
public abstract class BaseEntityService<T> where T : class
{
private readonly DbContext _Context;
private readonly IDbSet<T> _DbSet; public BaseEntityService(DbContext context)
{
this._Context = context;
_DbSet = _Context.Set<T>();
}
/// <summary>
/// 根据条件判断是否数据存在
/// </summary>
/// <param name="where">判断条件</param>
/// <returns></returns>
public bool HasInstance(Expression<Func<T, bool>> where)
{
if (_DbSet.Where(where).FirstOrDefault() != null)
return true;
else
return false;
}
/// <summary>
/// 根据条件判断是否数据存在
/// </summary>
/// <typeparam name="T2">需要判断实体</typeparam>
/// <param name="where">判断条件</param>
/// <returns></returns>
public bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>; ;
if (dbSet.Where(where).FirstOrDefault() != null)
return true;
else
return false;
}
/// <summary>
/// 根据主键ID获取实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T GetByIntID(int id)
{
return _DbSet.Find(id);
}
/// <summary>
/// 根据主键ID获取实体
/// </summary>
/// <param name="oid"></param>
/// <returns></returns>
public T GetByStringID(string oid)
{
return _DbSet.Find(oid);
}
/// <summary>
/// 根据主键ID获取实体
/// </summary>
/// <param name="oid"></param>
/// <returns></returns>
public T GetByGuid(Guid oid)
{
return _DbSet.Find(oid);
}
/// <summary>
/// 根据条件获取实体
/// </summary>
/// <param name="where">刷选条件</param>
/// <returns></returns>
public T GetByLambda(Expression<Func<T, bool>> where)
{ return _DbSet.Where(where).FirstOrDefault<T>();
} public T GetOrCreatePersistence(Guid id)
{
var fObject = this.GetByGuid(id);
if (fObject != null)
return fObject;
else
{
fObject = Activator.CreateInstance<T>();
this.Add(fObject);
return fObject;
}
} public T GetOrCreateNotPersistence(Guid id)
{
var fObject = this.GetByGuid(id);
if (fObject != null)
return fObject;
else
{
fObject = Activator.CreateInstance<T>();
return fObject;
}
}
/// <summary>
/// 添加数据
/// </summary>
/// <param name="bo">实体</param>
public void Add(T bo)
{
_DbSet.Add(bo);
_Context.SaveChanges();
}
/// <summary>
/// 添加或者更新数据
/// </summary>
/// <param name="bo">实体</param>
/// <param name="isForNewObject">是否新增</param>
/// <param name="updatedProperties">过滤字段</param>
public void AddOrUpdate(T bo, bool isForNewObject=true, params Expression<Func<T, object>>[] updatedProperties)
{
if (isForNewObject)
{
this.Add(bo);
}
else
{
this.Update(bo,updatedProperties);
}
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="bo">实体</param>
public void Delete(T bo)
{
_DbSet.Remove(bo);
_Context.SaveChanges();
} /// <summary>
/// 根据stringID删除数据
/// </summary>
/// <param name="id"></param>
public void Delete(string id)
{
_DbSet.Remove(GetByStringID(id));
_Context.SaveChanges();
}
/// <summary>
/// 根据主键ID删除数据(int)
/// </summary>
/// <param name="id"></param>
public void Delete(int id)
{
_DbSet.Remove(GetByIntID(id));
_Context.SaveChanges();
} //public void DeleteByLambda(Expression<Func<T, bool>> where)
//{
// _DbSet.Delete(where);
// _Context.SaveChanges();
//}
/// <summary>
/// 删除数据
/// </summary>
/// <typeparam name="T2"></typeparam>
/// <param name="relevanceBo"></param>
public void DeleteRelevenceObject<T2>(T2 relevanceBo)
{
var dbSet = _Context.Set(typeof(T2));
dbSet.Remove(relevanceBo);
_Context.SaveChanges();
}
/// <summary>
/// 根据刷选添加循环删除
/// </summary>
/// <typeparam name="T2">需要删除的实体</typeparam>
/// <param name="where">删除条件</param>
public void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2)); var tempCollection = dbSet as IQueryable<T2>;
foreach (var item in tempCollection.Where(where))
dbSet.Remove(item); _Context.SaveChanges();
}
/// <summary>
/// 更新实体
/// </summary>
/// <param name="bo">实体</param>
public void Update(T bo)
{
_DbSet.Attach(bo);
_Context.Entry(bo).State = EntityState.Modified;
_Context.SaveChanges();
}
/// <summary>
/// 更新实体,并过滤不需要更新列
/// </summary>
/// <param name="entity">实体</param>
/// <param name="updatedProperties">过滤不需要更实体数组</param>
public void Update(T entity, params Expression<Func<T, object>>[] updatedProperties)
{
_DbSet.Attach(entity);
var dbEntityEntry = _Context.Entry(entity);
_Context.Entry(entity).State = EntityState.Modified;
if (updatedProperties.Any())
{
foreach (var property in updatedProperties)
{
dbEntityEntry.Property(property).IsModified = false;
}
} _Context.SaveChanges(); }
/// <summary>
/// 获取实体所有信息
/// </summary>
/// <returns></returns>
public IQueryable<T> GetAll()
{
return _DbSet as IQueryable<T>;
}
/// <summary>
/// 获取实体信息并排序
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
public IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order)
{
return _DbSet.OrderBy(order);
}
/// <summary>
/// 筛选获取实体
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public IQueryable<T> GetMany(Expression<Func<T, bool>> where)
{
return _DbSet.Where(where) as IQueryable<T>;
} public IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val)
{
//var queryBuilder = CustomLinq.Func((selector, val) =>
// from c in _DbSet.ToExpandable()
// where selector.Expand(c).IndexOf(val) != -1
// select c);
return _DbSet as IQueryable<T>;
} public IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order)
{
return _DbSet.Where(where).OrderBy(order);
} public IQueryable<T> GetAllOrderedPaged(string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
{
var searchResult = _DbSet as IQueryable<T>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
return searchResult;
} public IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
{
var searchResult = _DbSet as IQueryable<T>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ;
return searchResult.OrderBy(order).Skip((page - ) * pageSize).Take(pageSize);
} public IQueryable<T> GetManyOrderedPaged<Tkey>(Expression<Func<T, bool>> where, Expression<Func<T, Tkey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
{
var searchResult = _DbSet.Where(where) as IQueryable<T>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ; if (!isDesc)
return searchResult.OrderBy(order).Skip((page - ) * pageSize).Take(pageSize);
else
return searchResult.OrderByDescending(order).Skip((page - ) * pageSize).Take(pageSize);
} ///// <summary>
///// 分页获取数据
///// </summary>
///// <param name="page">分页基础类</param>
///// <param name="dataAmount">输出总数量</param>
///// <param name="where">筛选条件</param>
///// <returns></returns>
//public IQueryable<T> GetDataPaging(GridPager page, ref int dataAmount, Expression<Func<T, bool>> where = null)
//{
// var searchResult = _DbSet as IQueryable<T>;
// if (where != null)
// searchResult = searchResult.Where(where);
// dataAmount = searchResult.Count();
// var isDesc = page.order == "desc";
// searchResult = searchResult.OrderBy(page.sort, isDesc).Skip(page.thisCount).Take(page.rows);
// return searchResult;
//} public IQueryable<T> GetManyOrderedByProertyNamePaged(
Expression<Func<T, bool>> where,
string orderProeprtyName,
int page,
int pageSize,
ref int pageAmount,
ref int boAmount,
ref bool isDesc
)
{
if (where != null)
{
var searchResult = _DbSet.Where(where) as IQueryable<T>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ; return searchResult;
}
else
{
var searchResult = _DbSet as IQueryable<T>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ; return searchResult;
} } public IQueryable<T> GetAllCommonWay(
ref int pageAmount,
ref int boAmount,
Expression<Func<T, bool>> where = null,
Expression<Func<T, bool>> order = null,
bool? isDesc = null,
int? page = null,
int? pageSize = null)
{
pageAmount = ;
boAmount = ;
var searchResult = _DbSet as IQueryable<T>; if (where != null && order != null)
{
searchResult = searchResult.Where(where);
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
else
{
if (where != null)
{
searchResult = searchResult.Where(where);
}
else
{
if (order != null)
{
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
}
} boAmount = searchResult.Count();
if (pageAmount == -)
{
pageAmount = -;
} if (page != null)
{
var p = (int)page;
var ps = (int)pageSize;
pageAmount = searchResult.Count() / ps;
searchResult = searchResult.Skip((p - ) * ps).Take(ps);
} return searchResult;
} public bool CanAdd(Expression<Func<T, bool>> where)
{
var count = _DbSet.Where(where).Count();
if (count > )
return false;
else
return true;
} public T2 GetRelevanceObject<T2>(Guid id)
{
var dbSet = _Context.Set(typeof(T2));
return (T2)dbSet.Find(id);
} public T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString)
{
var id = _Context.Database.SqlQuery<Guid>(SqlQureyString).FirstOrDefault();
if (id != null)
{
return GetRelevanceObject<T2>(id);
}
else
return default(T2);
} public T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>;
return (T2)dbSet.Where(where).FirstOrDefault();
} public IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where)
{
var dbSet = _Context.Set(typeof(T2));
var searchResult = dbSet as IQueryable<T2>; return searchResult.Where(where);
} public IQueryable<T2> GetRelevanceObjects<T2>(
Expression<Func<T2, bool>> where = null,
Expression<Func<T2, bool>> order = null,
bool? isDesc = null)
{
var dbSet = _Context.Set(typeof(T2));
var searchResult = dbSet as IQueryable<T2>;
if (where != null && order != null)
{
searchResult = searchResult.Where(where);
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
else
{
if (where != null)
{
searchResult = searchResult.Where(where);
}
else
{
if (order != null)
{
if (isDesc != null)
searchResult = searchResult.OrderByDescending(order);
else
searchResult = searchResult.OrderBy(order);
}
}
} return searchResult;
} public IQueryable<T2> GetManyRelevanceObjectsOrderedByProertyNamePaged<T2>(
Expression<Func<T2, bool>> where,
string orderProeprtyName,
int page,
int pageSize,
ref int pageAmount,
ref int boAmount,
ref bool isDesc)
{
var dbSet = _Context.Set(typeof(T2)); if (where != null)
{
var searchResult = (dbSet as IQueryable<T2>).Where(where) as IQueryable<T2>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ; return searchResult;
}
else
{
var searchResult = dbSet as IQueryable<T2>;
boAmount = searchResult.Count();
pageAmount = boAmount / pageSize;
if (boAmount > pageAmount * pageSize)
pageAmount = pageAmount + ; return searchResult;
} } public void AddRelevanceObject<T2>(T2 relevanceBo)
{
var dbSet = _Context.Set(typeof(T2));
dbSet.Add(relevanceBo);
_Context.SaveChanges();
} public void UpdateRelevanceObject<T2>(T2 relevanceBo)
{
var tempBo = Activator.CreateInstance(typeof(T2));
tempBo = relevanceBo;
var dbSet = _Context.Set(typeof(T2));
dbSet.Attach(tempBo);
_Context.Entry(tempBo).State = EntityState.Modified;
_Context.SaveChanges();
} }

通过以上步骤,一个基本简单的仓储完成了。

接下来一般的话,是使用三层Model,DAL,BLL,由于我个人比较懒,直接跳过了DAL层,在BLL层进行业务处理。

新建一个ArticleBLL,对业务的操作。

 public class ArticleBLL : BaseEntityService<ZWStar_Article>, IBaseEntityService<ZWStar_Article>
{
public ArticleBLL() : base(EFDbContext.GetDbContext()) { }
}

此刻,基本的仓储完成,下篇将介绍如果结合layui完成菜单的添加

ASP.net MVC 构建layui管理后台(构造基础仓储)<1>的更多相关文章

  1. ASP.net MVC 构建layui管理后台(整体效果)

    登录页: 首页 模块管理 角色管理,角色分配 用户管理

  2. 在Asp.Net MVC中用Ajax回调后台方法

    在Asp.Net MVC中用Ajax回调后台方法基本格式: var operData = ...; //传递的参数(action中定义的) var type = ...; //传递的参数(action ...

  3. 26、ASP.NET MVC入门到精通——后台管理区域及分离、Js压缩、css、jquery扩展

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 有好一段时间没更新博文了,最近在忙两件事:1.看书,学习中...2.为公司年会节目做准备,由于许久没有练习双截棍了,难免生疏,所以现在临时抱 ...

  4. ASP.NET MVC实现layui富文本编辑器应用

    先看看视图层 在视图层,使用的是视图助手--HtmlHelper,代替我们网页中传统的表单标签元素,其中的m代表实体模型.通过视图助手,为我们生成id和name属性相同的textarea标签. 备注: ...

  5. asp.net mvc的权限管理设计

    现在集中展示用户-角色-权限管理的功能,因此,所有数据表一律简化处理.   1 后台管理效果 (1)角色管理 (2)权限管理   2 数据库设计(MSSQL) (1)用户表dbo.Users 项 类型 ...

  6. GPS部标平台的架构设计(十)-基于Asp.NET MVC构建GPS部标平台

    在当前很多的GPS平台当中,有很多是基于asp.NET+siverlight开发的遗留项目,代码混乱而又难以维护,各种耦合和关联,要命的是界面也没见到比Javascript做的控件有多好看,随着需求的 ...

  7. 关于 ASP.NET MVC 4 如果管理用户

    很久没上来写博客,因为自己没写博客的日子里去学了一下OBJECTIVE-C 和 ASP.NET MVC.最近在学ASP.NET MVC 4,有个问题一直在困扰着我,就是怎样管理用SIMPLE MEMB ...

  8. asp.net mvc中的后台验证

    asp.net mvc的验证包含后台验证和前端验证.后台验证主要通过数据注解的形式实现对model中属性的验证,其验证过程发生在model绑定的过程中.前端验证是通过结合jquery.validate ...

  9. 【转】ASP.NET MVC教程

    转自:http://www.cnblogs.com/QLeelulu/category/123326.html ASP.NET MVC的最佳实践与性能优化的文章 摘要: 就一些文章链接,就不多废话了. ...

随机推荐

  1. org.apache.http.NoHttpResponseException

    org.apache.http.NoHttpResponseException 异常: org.apache.http.NoHttpResponseException: The target serv ...

  2. rancher1.6高可用集群搭建

    rancher高可用集群搭建 一.搭建环境 1.安装系统 下载centos最新版, http://mirrors.sohu.com/centos/7/isos/x86_64/CentOS-7-x86_ ...

  3. 格式化MyEclipse代码(java、jsp、js)行的长度@修改java代码字体@修改Properties文件编码方式

    每次用MyEclipse/Eclipse自带的快捷键Ctrl+shift+f格式化代码时,如果原来的一行代码大于80列,Eclipse就会自动换为多行.如果想格式化代码后不想让代码换行可以通过以下方式 ...

  4. python入门机器学习,3行代码搞定线性回归

    本文着重是重新梳理一下线性回归的概念,至于几行代码实现,那个不重要,概念明确了,代码自然水到渠成. “机器学习”对于普通大众来说可能会比较陌生,但是“人工智能”这个词简直是太火了,即便是风云变化的股市 ...

  5. IP地址0.0.0.0表示什么

    参考RFC文档: 0.0.0.0/8 - Addresses in this block refer to source hosts on "this"network. Addre ...

  6. 马云也看好!VR在2016年能否得到质变

    在2015年10月底有消息传出,国外虚拟现实公司Magic Lea的新一轮融资吸引到中国互联网巨鳄--阿里巴巴公司的关注.据透露,阿里巴巴极有可能为Magic Lea投资2亿美元.这虽然是阿里巴巴第一 ...

  7. redis BLPOP

    一.需求 redis中保存了需要download的image url,存储格式为列表. 我需要从列表中获取数据,将图片下载保存到本地. 列表中的数据是一直增加的. 二.实现 使用redis BLPOP ...

  8. 先搞清楚这些问题,简历上再写你熟悉Java!

    原创声明 本文作者:黄小斜 转载请务必在文章开头注明出处和作者. 系列文章介绍 本文是<五分钟学Java>系列文章的一篇 本系列文章主要围绕Java程序员必须掌握的核心技能,结合我个人三年 ...

  9. 浅谈ConcurrentDictionary与Dictionary

    在.NET4.0之前,如果我们需要在多线程环境下使用Dictionary类,除了自己实现线程同步来保证线程安全外,我们没有其他选择.很多开发人员肯定都实现过类似的线程安全方案,可能是通过创建全新的线程 ...

  10. 7-4 jmu-python-判断是否构成三角形 (10 分)

    7-4 jmu-python-判断是否构成三角形 (10 分)   输入三角形的三边,判断是否能构成三角形.若能构成输出yes,否则输出no. 输入格式: 在一行中直接输入3个整数,3个整数之间各用一 ...