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

.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.csdn.net/pukuimin1226/
本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值