作者微信 bishe2022

代码功能演示视频在页面下方,请先观看;如需定制开发,联系页面右侧客服
.Net框架搭建之1、SQL Server EF MVC简单三层框架

Custom Tab

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




转载自:http://blog.csdn.net/pukuimin1226/article/details/52313656

Home