.Net框架搭建之1、SQL Server EF MVC简单三层框架

本文详细介绍如何搭建.NET简单三层框架项目,包括数据模型Model层、DAL数据访问层、BLL逻辑处理层及MVC Web表示层的创建过程。

.Net简单三层框架简介

简单三层框架,是.Net开发中最最基础的框架了,由 数据访问层、逻辑处理层、表示层组成。一般情况下,在项目中数据模型Model层也是单独一层,但是只是单纯的数据模型不算在业务层划分当中。
好了,框架搭建,如果不了解,可能会觉得难以下手,了解之后,自然知道怎么做,只是其中的步骤,比起单纯的功能开发,是要繁琐不少,下面我们来一步一步搭建属于自己的框架,这里只列出重要步骤,其他未提到的细节可自行摸索。

数据模型Model层创建

数据模型层,首先要创建数据库,再从数据库生成EF模型。

创建数据库,表,添加一条测试数据

数据库创建

数据表添加

测试数据添加

新建类库,添加实体数据模型,连接数据库,获取表结构到实体模型

首先,添加类库 ,名称:Example.Model
再添加实体数据模型:
加实体数据模型
填写数据库连接参数
改模型命名空间
更新数据库表到模型

至此,Model数据层算了完成了。

DAL数据访问层创建

由于我们事件知道有几层,所以,先把所有的类库项目全部先建立好,web为MVC的空项目,至于各层代码,分到各层再去处理
各层对应的类库创建
项目间引用关系

由于使用EF,为了方便使用EF扩展,先用nuget添加一个扩展包
EntityFrameWork.Extended,版本使用默认的就行。
这里写图片描述

添加好之后,就可以添加一个BaseDAL的类了,是为了方便DAL层操作的。

BaseDAL.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using EntityFramework.Extensions;
using Example.Model;

namespace Example.DAL
{
    public class BaseDAL<T> where T : class
    {
        private ExampleEntities _db = null;
        public ExampleEntities db
        {
            get
            {
                if (_db == null) _db = new ExampleEntities();
                return _db;
            }
        }

        public virtual IQueryable<T> Entities
        {
            get { return db.Set<T>().AsNoTracking(); }
        }

        public virtual IQueryable<T> Table
        {
            get { return db.Set<T>(); }
        }
        public IList<T> GetAll(Expression<Func<T, bool>> exp)
        {
            var query = db.Set<T>().Where(exp).AsNoTracking();
            IList<T> data = query.ToList();
            return data;
        }

        public int Add(T model)
        {
            try
            {
                EntityState state = db.Entry(model).State;
                if (state == EntityState.Detached)
                {
                    db.Entry(model).State = EntityState.Added;
                }
                //db.Set<T>().Add(model);
                return db.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string errmsg = "";
                foreach (var item in ex.EntityValidationErrors.First().ValidationErrors)
                {
                    errmsg += item.ErrorMessage + " ; ";
                }
                throw new Exception(errmsg);
            }
            finally
            {

            }
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public int AddCollect(List<T> models)
        {
            try
            {
                foreach (T model in models)
                {
                    EntityState state = db.Entry(model).State;
                    if (state == EntityState.Detached)
                    {
                        db.Entry(model).State = EntityState.Added;
                    }
                }
                //db.Set<T>().Add(model);
                return db.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string errmsg = "";
                foreach (var item in ex.EntityValidationErrors.First().ValidationErrors)
                {
                    errmsg += item.ErrorMessage + " ; ";
                }
                throw new Exception(errmsg);
            }
            finally
            {

            }
        }
        public int Edit(T model)
        {
            try
            {
                try
                {
                    db.Set<T>().Attach(model);
                }
                catch { }
                db.Entry(model).State = EntityState.Modified;
                return db.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string errmsg = "";
                foreach (var item in ex.EntityValidationErrors.First().ValidationErrors)
                {
                    errmsg += item.ErrorMessage + " ; ";
                }
                throw new Exception(errmsg);
            }
            finally
            {

            }
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public int EditCollect(List<T> models)
        {
            try
            {
                foreach (T model in models)
                {
                    try
                    {
                        EntityState state = db.Entry(model).State;
                        db.Set<T>().Attach(model);
                    }
                    catch { }
                    db.Entry(model).State = EntityState.Modified;
                }
                return db.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string errmsg = "";
                foreach (var item in ex.EntityValidationErrors.First().ValidationErrors)
                {
                    errmsg += item.ErrorMessage + " ; ";
                }
                throw new Exception(errmsg);
            }
            finally
            {

            }
        }
        /// <summary>
        /// 修改操作,可以只更新部分列,效率高
        /// </summary>
        /// <param name="funWhere">查询条件-谓语表达式</param>
        /// <param name="funUpdate">实体-谓语表达式</param>
        /// <returns>操作影响的行数</returns>
        public virtual int Edit(Expression<Func<T, bool>> funWhere, Expression<Func<T, T>> funUpdate)
        {
            return Entities.Where(funWhere).Update(funUpdate);
        }
        public int Delete(T model)
        {
            try
            {
                db.Configuration.AutoDetectChangesEnabled = false;
                db.Entry(model).State = EntityState.Deleted;
                db.Configuration.AutoDetectChangesEnabled = true;
                return db.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string errmsg = "";
                foreach (var item in ex.EntityValidationErrors.First().ValidationErrors)
                {
                    errmsg += item.ErrorMessage + " ; ";
                }
                throw new Exception(errmsg);
            }
            finally
            {

            }
        }
        public int DeleteExp(Expression<Func<T, bool>> exp)
        {
            try
            {
                var q = db.Set<T>().Where(exp);
                db.Configuration.AutoDetectChangesEnabled = false;
                db.Set<T>().RemoveRange(q);
                db.Configuration.AutoDetectChangesEnabled = true;
                return db.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string errmsg = "";
                foreach (var item in ex.EntityValidationErrors.First().ValidationErrors)
                {
                    errmsg += item.ErrorMessage + " ; ";
                }
                throw new Exception(errmsg);
            }
            finally
            {

            }
        }
    }
}

有了BaseDAL这个类,我们就来建立具体针对表的 SysUserDAL.cs

SysUserDAL.cs
很简单,我们就写个方法读取数据库中之前添加的一条测试数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace Example.DAL
{
    public class SysUserDAL : BaseDAL<SysUser>
    {
        public SysUser GetUserById(int id)
        {
            return Entities.Where(o => o.Id == id).FirstOrDefault();
        }
    }
}

BLL逻辑处理层创建

在Example.BLL 项目中,添加 Example.BLL.cs

Example.BLL.cs

using Example.DAL;
using Example.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Example.BLL
{
    public class SysUserBLL
    {
        private SysUserDAL _dal = null;
        public SysUserDAL dal
        {
            get
            {
                if (_dal == null) _dal = new SysUserDAL();
                return _dal;
            }
        }
        public SysUser GetUserById(int id)
        {
            return dal.GetUserById(id);
        }
    }
}

BLL层内容也就完成了

BLL层就这么简单,如果不做数据方面的判断,直接调用DAL层的方法就行

MVC Web 表示层处理

先简单修改一下默认路由

配置路由默认访问地址为Index

创建首页控制器和页面Razor视图

控制器和视图

Index控制器中修改action为Index的方法

        private SysUserBLL _BLL = null;
        public SysUserBLL BLL
        {
            get
            {
                if (_BLL == null) _BLL = new SysUserBLL();
                return _BLL;
            }
        }
        //
        // GET: /Index/
        public ActionResult Index()
        {
            ViewBag.FirstUser = BLL.GetUserById(1);
            return View();
        }

Index.cshtml页面显示的修改

@{
    Layout = null;
    var model = ViewBag.FirstUser as Example.Model.SysUser;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <div>
        姓名:@(model!=null?model.UserName:"空")
    </div>
</body>
</html>

运行效果:
最终效果

此文章一步一步介绍如果搭建简单三层 ef mvc框架项目,关键流程和代码都已贴上,按步骤来应该可以正常运行,如果不能正常运行,可以同我交流,可以加补一些更详细的步骤。

后续会加上另外几种框架。

版权声明:
作者:真爱无限
出处:http://blog.youkuaiyun.com/pukuimin1226/
本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.

在刚刚步入“多层结构”Web应用程序开发的时候,我阅读过几篇关于“asp.net三层结构开发”的文章。但其多半都是对PetShop3.0和Duwamish7的局部剖析或者是学习笔记。对“三层结构”通体分析的学术文章几乎没有。 2005年2月11日,Bincess BBS彬月论坛开始试运行。不久之后,我写了一篇题目为《浅谈“三层结构”原理与用意》的文章。旧版文章以彬月论坛程序中的部分代码举例,通过全局视角阐述了什么是“三层结构”的开发模式?为什么要这样做?怎样做?……而在这篇文章的新作中,配合这篇文章我写了7个程序实例(TraceLWord1~TraceLWord7留言板)以帮助读者理解“三层结构”应用程序。这些程序示例可以在随带的CodePackage目录中找到——   对于那些有丰富经验的Web应用程序开发人员,他们认为文章写的通俗易懂,很值得一读。可是对于asp.net初学者,特别是没有任何开发经验的人,文章阅读起来就感到非常困难,不知文章所云。甚至有些读者对“三层结构”的认识更模糊了……   关于“多层结构”开发模式,存在这样一种争议:一部分学者认为“多层结构”与“面向对象的程序设计思想”有着非常紧密的联系。而另外一部分学者却认为二者之间并无直接联系。写作这篇文章并不是要终结这种争议,其行文目的是希望读者能够明白:在使用asp.net进行Web应用程序开发时,实现“多层结构”开发模式的方法、原理及用意。要顺利的阅读这篇文章,希望读者能对“面向对象的程序设计思想”有一定深度的认识,最好能懂一些“设计模式”的知识。如果你并不了解前面这些,那么这篇文章可能并不适合你现在阅读。不过,无论这篇文章面对的读者是谁,我都会尽量将文章写好。我希望这篇文章能成为学习“三层结构”设计思想的经典文章!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值