三层架构与MVC的关系

三层架构是一个分层式的软件体系架构设计,分为:表现层(UI)、业务逻辑层(BLL)、数据访问层(DAL)。分层的目的是为了实现“高内聚,低耦合”的思想,有利于系统后期的维护、更新或者移植。

MVC是一个设计模式,分为:MVC 即Model(模型),View(视图),Controller(控制)

MVC与三层架构不是一个等级的。我个人认为MVC其实就是把三层中的UI层又细分成了三层而已

开发环境

vs2013+mvc5+ef6+sql2008

解决方案设计

  • Common:共用类库
  • cms.BLL:逻辑层,引用DAL、Model
  • cms.DAL:数据访问层,引用Model
  • cms.Model:实体层,对应数据库
  • cms.Web:UI显示层(MVC),引用Common、BLL、Model

算是比较简单的三层+MVC,先看下框架

Common:常用类库

因为用到了缓存,所以发下缓存类代码

CacheHelper.cs

using System;
using System.Web;
using System.Collections; namespace Common
{
/// <summary>
/// Cache辅助类
/// </summary>
public class CacheHelper
{
/// <summary>
/// 获取数据缓存
/// </summary>
/// <param name="CacheKey">键</param>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject);
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
} /// <summary>
/// 移除指定数据缓存
/// </summary>
public static void RemoveCache(string CacheKey)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
_cache.Remove(CacheKey);
} /// <summary>
/// 移除全部缓存
/// </summary>
public static void RemoveCache()
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
_cache.Remove(CacheEnum.Key.ToString());
}
}
}
}

cms.Model:实体层

model层使用dbfirst模式生成

生成后把app.config里的数据库链接字符串复制到mvc网站web.config中

cms.DAL:数据访问层

ContextFactory

using cms.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks; namespace cms.DAL
{
/// <summary>
/// 上下文简单工厂
/// </summary>
public class ContextFactory
{
/// <summary>
/// 获取当前数据上下文
/// </summary>
/// <returns></returns>
public static dbEntities GetCurrentContext()
{
dbEntities _nContext = CallContext.GetData("dbEntities") as dbEntities;
if (_nContext == null)
{
_nContext = new dbEntities();
CallContext.SetData("dbEntities", _nContext);
}
return _nContext;
}
}
}

BaseDAL

using cms.Model;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace cms.DAL
{
/// <summary>
/// DAL基类
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class BaseDAL<T> where T : class, new()
{
public dbEntities dbContext = ContextFactory.GetCurrentContext();
public T Add(T entity)
{
dbContext.Set<T>().Add(entity);
dbContext.SaveChanges();
return entity;
}
public int AddRange(IEnumerable<T> entities)
{
dbContext.Set<T>().AddRange(entities);
return dbContext.SaveChanges();
}
public bool Delete(object id)
{
Type t = typeof(T);
string tableName = t.Name;
string sql = string.Format("delete from {0} where id=@ID", tableName);
SqlParameter[] paras = new SqlParameter[]
{
new SqlParameter("@ID",id)
};
return dbContext.Database.ExecuteSqlCommand(sql, paras) > ;
}
public bool Delete(T entity)
{
dbContext.Set<T>().Attach(entity);
dbContext.Entry<T>(entity).State = System.Data.Entity.EntityState.Deleted;
return dbContext.SaveChanges() > ;
}
public bool DeleteList(string idList)
{
Type t = typeof(T);
string tableName = t.Name;
string sql = string.Format("delete from {0} where id in(" + idList + ")", tableName);
return dbContext.Database.ExecuteSqlCommand(sql) > ;
}
public bool Update(T entity)
{
dbContext.Set<T>().Attach(entity);
dbContext.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
return dbContext.SaveChanges() > ;
}
public int Count()
{
return dbContext.Set<T>().Count();
}
public int Count(Expression<Func<T, bool>> predicate)
{
return dbContext.Set<T>().Count(predicate);
}
public bool Exist(Expression<Func<T, bool>> anyLambda)
{
return dbContext.Set<T>().Any(anyLambda);
}
public T Find(object id)
{
T _entity = dbContext.Set<T>().Find(id);
return _entity;
}
public T Find(Expression<Func<T, bool>> whereLambda)
{
T _entity = dbContext.Set<T>().FirstOrDefault<T>(whereLambda);
return _entity;
} public T GetModelByCache(object id)
{
Type t = typeof(T);
string tableName = t.Name;
string CacheKey = tableName + "Model-" + id;
object objModel = Common.CacheHelper.GetCache(CacheKey);
if (objModel == null)
{
try
{
objModel = Find(id);
if (objModel != null)
{
int ModelCache = ;//5分钟
Common.CacheHelper.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
}
}
catch { objModel = Find(id); }
}
return (T)objModel;
}
/// <summary>
/// 查找对象列表
/// </summary>
/// <typeparam name="S"></typeparam>
/// <returns></returns>
public IQueryable<T> FindList()
{
return dbContext.Set<T>().AsQueryable();
}
/// <summary>
/// 查找对象列表:bll.FindList(x => x.ID > 25, true, x => x.ID);
/// </summary>
/// <typeparam name="S"></typeparam>
/// <param name="whereLamdba">条件,空设置为null</param>
/// <param name="isAsc">是否正序</param>
/// <param name="orderLamdba">排序字段</param>
/// <returns></returns>
public IQueryable<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba)
{
var _list = dbContext.Set<T>().AsQueryable();
if (whereLamdba != null)
{
_list = _list.Where<T>(whereLamdba);
}
if (isAsc) _list = _list.OrderBy<T, S>(orderLamdba);
else _list = _list.OrderByDescending<T, S>(orderLamdba);
return _list;
}
/// <summary>
/// 数据分页:bll.FindPageList(pageIndex, pageSize, out totalItem, x => x.ID > 1, false, x => x.ID);
/// </summary>
/// <typeparam name="S"></typeparam>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecord"></param>
/// <param name="whereLamdba"></param>
/// <param name="isAsc"></param>
/// <param name="orderLamdba"></param>
/// <returns></returns>
public IQueryable<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba)
{
var _list = dbContext.Set<T>().Where<T>(whereLamdba);
totalRecord = _list.Count();
if (isAsc) _list = _list.OrderBy<T, S>(orderLamdba).Skip<T>((pageIndex - ) * pageSize).Take<T>(pageSize);
else _list = _list.OrderByDescending<T, S>(orderLamdba).Skip<T>((pageIndex - ) * pageSize).Take<T>(pageSize);
return _list;
}
}
}

adminDAL,继承 BaseDAL

using cms.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace cms.DAL
{
public partial class adminDAL : BaseDAL<admin>
{
//扩展方法添加在这里 //public IEnumerable<admin> AddRange(IEnumerable<admin> entities)
//{
// dbContext.Set<admin>().AddRange(entities);
// dbContext.SaveChanges();
// return entities;
//}
}
}

cms.BLL:逻辑层

BaseBLL

using cms.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace cms.BLL
{
/// <summary>
/// BLL基类
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract partial class BaseBLL<T> where T : class, new()
{
protected BaseDAL<T> Dal = new BaseDAL<T>(); /// <summary>
/// 添加
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public T Add(T entity) { return Dal.Add(entity); } /// <summary>
/// 添加集合
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public int AddRange(IEnumerable<T> entities) { return Dal.AddRange(entities); } /// <summary>
/// 删除
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Delete(T entity) { return Dal.Delete(entity); } /// <summary>
/// 根据ID删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool Delete(object id) { return Dal.Delete(id); } /// <summary>
/// 根据ID批量删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool DeleteList(string idList) { return Dal.DeleteList(idList); } /// <summary>
/// 修改
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Update(T entity) { return Dal.Update(entity); } /// <summary>
/// 统计
/// </summary>
/// <returns></returns>
public int Count()
{
return Dal.Count();
} /// <summary>
/// 统计
/// </summary>
/// <param name="anyLambda"></param>
/// <returns></returns>
public int Count(Expression<Func<T, bool>> anyLambda)
{
return Dal.Count(anyLambda);
} /// <summary>
/// 是否存在该记录
/// </summary>
/// <param name="anyLambda"></param>
/// <returns></returns>
public bool Exist(Expression<Func<T, bool>> anyLambda)
{
return Dal.Exist(anyLambda);
} /// <summary>
/// 根据ID查找
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T Find(object id)
{
return Dal.Find(id);
} /// <summary>
/// 根据lambda查找
/// </summary>
/// <param name="whereLambda"></param>
/// <returns></returns>
public T Find(Expression<Func<T, bool>> whereLambda)
{
return Dal.Find(whereLambda);
} /// <summary>
/// 从缓存中得到一个对象实体,缓存5分钟
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T GetModelByCache(object id)
{
return Dal.GetModelByCache(id);
}
/// <summary>
/// 查找集合
/// </summary>
/// <typeparam name="S"></typeparam>
/// <returns></returns>
public IQueryable<T> FindList()
{
return Dal.FindList();
}
/// <summary>
/// 查找集合,使用方法:bll.FindList(x => x.ID > 10, true, x => x.ID);
/// </summary>
/// <typeparam name="S"></typeparam>
/// <param name="whereLamdba"></param>
/// <param name="isAsc"></param>
/// <param name="orderLamdba"></param>
/// <returns></returns>
public IQueryable<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba)
{
return Dal.FindList(whereLamdba, isAsc, orderLamdba);
} /// <summary>
/// 分页,使用方法:bll.FindPageList(pageIndex, pageSize, out totalItem, x => x.ID > 1, false, x => x.ID);
/// </summary>
/// <typeparam name="S"></typeparam>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecord"></param>
/// <param name="whereLamdba"></param>
/// <param name="isAsc"></param>
/// <param name="orderLamdba"></param>
/// <returns></returns>
public IQueryable<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba)
{
return Dal.FindPageList(pageIndex, pageSize, out totalRecord, whereLamdba, isAsc, orderLamdba);
}
}
}

adminBLL,继承 BaseBLL

using cms.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace cms.BLL
{
public partial class adminBLL : BaseBLL<admin>
{
//扩展方法添加在这里 //protected adminDAL mydal=new adminDAL(); //public IEnumerable<admin> AddRange(IEnumerable<admin> entities)
//{
// return mydal.AddRange(entities);
//}
}
}

cms.Web:MVC5

引用Common、BLL、Model

简单用法

            adminBLL bll = new adminBLL();
admin model = new admin(); //Add
model.username = "admin";
model.password = "";
bll.Add(model); //Delete
model = bll.Find();
bll.Delete(model);//删除对象 bll.Delete();//根据ID删除对象 //update
bll.Update(model); //find
model = bll.Find();//找一个对象
model = bll.GetModelByCache();//从缓存中找一个对象,默认缓存5分钟,在dal设置

//在实际项目开发中会有很多表,手动写dal和bll不现实,可使用t4+Model.edmx生成 https://www.cnblogs.com/webapi/p/10452095.html

Asp.Net MVC简单三层架构(MVC5+EF6)的更多相关文章

  1. 转载——Asp.Net MVC+EF+三层架构的完整搭建过程

    转载http://www.cnblogs.com/zzqvq/p/5816091.html Asp.Net MVC+EF+三层架构的完整搭建过程 架构图: 使用的数据库: 一张公司的员工信息表,测试数 ...

  2. asp.net mvc 加三层架构 完美搭配

    http://www.hysql.org/aspnet/20180630/5712.html 先来一张项目的层级结构图: Model:模型层,主要是各种类型.枚举以及ORM框架,框架完成数据库和实体类 ...

  3. Asp.Net MVC<一> : 三层架构、MVC

    MVC.MVP.MVVM.Angular.js.Knockout.js.Backbone.js.React.js.Ember.js.Avalon.js.Vue.js 概念摘录 认清Android框架 ...

  4. Asp.Net MVC+EF+三层架构的完整搭建过程

    架构图: 使用的数据库: 一张公司的员工信息表,测试数据 解决方案项目设计: 1.新建一个空白解决方案名称为Company 2.在该解决方案下,新建解决方案文件夹(UI,BLL,DAL,Model) ...

  5. Asp.Net MVC+EF+三层架构

    架构图: 使用的数据库: 一张公司的员工信息表,测试数据 解决方案项目设计: 1.新建一个空白解决方案名称为Company 2.在该解决方案下,新建解决方案文件夹(UI,BLL,DAL,Model) ...

  6. MVC和三层架构

    从最开始写程序到现在,一路上听到架构这个词已经无数次了,在工作和圈子里也不停听到大家在讨论它,但是很多时候发现不少人对这个概念的理解都是很模糊的,无意间在知道上看到一个朋友的回答,感觉很不错,特转帖到 ...

  7. Net系列框架-Dapper+简单三层架构

    Net系列框架-Dapper+简单三层架构 工作将近6年多了,工作中也陆陆续续学习和搭建了不少的框架,后续将按由浅入深的方式,整理出一些框架源码,所有框架源码本人都亲自调试通过,如果有问题,欢迎联系我 ...

  8. mvc和三层架构到底有什么区别

    原文地址:http://zhidao.baidu.com/question/82001542.html?qbl=relate_question_3&word=MVC%20%CA%FD%BE%D ...

  9. 从MVC和三层架构说到SSH整合开发

    相信很多人都认同JavaWeb开发是遵从MVC开发模式的,遵从三层架构进行开发的,是的,大家都这么认同.但是相信大家都会有过这样一个疑问,if(MVC三层模式==三层架构思想)out.println( ...

随机推荐

  1. Struts2常见配置(草稿)

    Struts2框架配置文件加载的顺序(了解加载配置文件的顺序,重点掌握struts.xml配置文件) 1.Struts2框架的核心是StrutsPrepareAndExecuteFilter过滤器,该 ...

  2. std::thread 不 join

    std::thread 构造之后 使用 detach.就可以了

  3. App 开发步骤

    在 iOS 开发中,写一个 App 很容易,但是要写好一个 App,确是要下另一番功夫.首先,我们来看一个 App 的开发要求: 写一个 App,显示出 Spotify 上 Lady Gaga 相关的 ...

  4. 原创工具binlog2sql:从MySQL binlog得到你要的SQL

    从MySQL binlog得到你要的SQL.根据不同设置,你可以得到原始SQL.回滚SQL.去除主键的INSERT SQL等. 用途 数据回滚 主从切换后数据不一致的修复 从binlog生成标准SQL ...

  5. C++下的命名空间

    转自:http://blog.chinaunix.net/uid-24219701-id-2105573.html 实例: #include <iostream> using namesp ...

  6. xcode9报错 Safe Area Layout Guide before iOS9.0

    运行工程的时候会遇到  Safe Area Layout Guide before iOS9.0 这是因为xcode9  storyboard的设置里面多了 个 Safe Area Layout Gu ...

  7. SDL操作笔记

    原文地址:https://blog.csdn.net/qq_38124598/article/details/73543184 这里总结一下个人对SDL的一些函数,方便以后查询.   v1.0.1 1 ...

  8. log4j(二)——如何控制日志信息的输出?

    一:测试环境与log4j(一)——为什么要使用log4j?一样,这里不再重述 二:先看栗子再来下结论 import org.apache.log4j.*; import test.log4j.bean ...

  9. Ubuntu18.04 修改DNS

    Ubuntu18.04 修改DNS sudo vim /etc/systemd/resolved.conf 修改如下: [Resolve] DNS=119.29.29.29 保存退出后 systemc ...

  10. 如何获取 docker 容器(container)的 ip 地址(转)

    1. 进入容器内部后 cat /etc/hosts 会显示自己以及(– link)软连接的容器IP 2.使用命令 docker inspect --format '{{ .NetworkSetting ...