Asp.Net MVC+EF+三層架構的完整搭建過程


2018.11.3 更新:

謝謝各位觀看 如果幫助到你了 我也很高興,這是我兩年前寫的文章了,當時自己也在學習,工作了以后才發現  這個搭建的框架還有很多的缺點,當然入門的話絕對是夠了,但是還是推薦下 有興趣的可以去學習下ABP。

如果遇到問題的話,可以去github上看一下,在文章最后有鏈接的,當時寫的時候,我自己試過的 是可以跑起來的噢。

架構圖:

使用的數據庫:

一張公司的員工信息表,測試數據

解決方案項目設計:

1.新建一個空白解決方案名稱為Company

2.在該解決方案下,新建解決方案文件夾(UI,BLL,DAL,Model) 當然還可以加上common

3.分別在BLL,DAL,Model 解決方案文件夾下創建類庫項目

(1).BLL解決方案文件夾: Company.BLL、Company.IBLL、Company.BLLContainer

(2).DAL解決方案文件夾: Company.DAL、Company.IDAL、Company.DALContainer

(3).Model解決方案文件夾:Company.Model

4.在UI 解決方案文件夾下添加一個ASP.NET Web應用程序,名稱為Company.UI,選擇我們的Mvc模板. 如圖:

Model層: 選中Company.Model,右鍵=>添加=>新建項=>添加一個ADO.NET實體數據模型名稱為Company=>選擇來自數據庫的EF設計器=>新建連接=>選擇我們的Company數據庫填入相應的內容

選擇我們的Staff表,完成后如圖:


這時Model層已經完成.我們的數據庫連接字符串以及ef的配置都在App.Config里,但我們項目運行的是我們UI層的Web應用程序,所以我們這里要把App.Config里的配置復制到UI層的Web.Config中 數據訪問層: 因為每一個實體都需要進行增刪改查,所以我們這里封裝一個基類.選中Company.IDAL,右鍵=>添加一個名稱為IBaseDAL的接口=>寫下公用的方法簽名

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
 
namespace Company.IDAL
{
    public partial interface IBaseDAL<T> where T : class, new()
    {
        void Add(T t);
        void Delete(T t);
        void Update(T t);
        IQueryable<T> GetModels(Expression<Func<T, bool>> whereLambda);
        IQueryable<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc, Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda);
        /// <summary>
        /// 一個業務中有可能涉及到對多張表的操作,那么可以將操作的數據,打上相應的標記,最后調用該方法,將數據一次性提交到數據庫中,避免了多次鏈接數據庫。
        /// </summary>
        bool SaveChanges();
    }
}

基類接口封裝完成.然后選中Company.IDAL,右鍵=>添加一個名稱為IStaffDAL的接口=>繼承自基類接口

 

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.Model;
 
namespace Company.IDAL
{
    public partial  interface IStaffDAL:IBaseDAL<Staff>
    {
    }
}

IDAL完成,接下來是DAL 選中Company.DAL=>右鍵=>添加一個類,名稱為:BaseDAL,該類是我們對IBaseDAL具體的實現,我們這里需要用到ef上下文對象,所以添加引用EntityFramework.dll和EntityFramework.SqlServer.dll(這里是ef6版本不同引用的dll也可能不同) 上面說到我們這里要用到ef下上文對象,我們這里不能直接new,因為這樣的話可能會造成數據混亂,所以要讓ef上下文對象保證線程內唯一。 我們選中Company.DAL=>右鍵=>添加一個類.名稱為DbContextFactory.通過這個類才創建ef上下文對象.

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using Company.Model;
 
namespace Company.DAL
{
    public partial class DbContextFactory
    {
        /// <summary>
        /// 創建EF上下文對象,已存在就直接取,不存在就創建,保證線程內是唯一。
        /// </summary>
        public static DbContext Create()
        {
            DbContext dbContext = CallContext.GetData("DbContext") as DbContext;
            if (dbContext==null)
            {
                dbContext=new CompanyEntities();
                CallContext.SetData("DbContext",dbContext);
            }
            return dbContext;
        }
    }
}

EF上下文對象創建工廠完成,這時我們來完成我們的BaseDAL

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.IDAL;
using System.Linq.Expressions;
 
namespace Company.DAL
{
    public partial class BaseDAL<T> where T : class, new()
    {
        private DbContext dbContext = DbContextFactory.Create();
        public void Add(T t)
        {
            dbContext.Set<T>().Add(t);
        }
        public void Delete(T t)
        {
            dbContext.Set<T>().Remove(t);
        }
 
        public void Update(T t)
        {
            dbContext.Set<T>().AddOrUpdate(t);
        }
 
        public IQueryable<T> GetModels(Expression<Func<T, bool>> whereLambda)
        {
            return dbContext.Set<T>().Where(whereLambda);
        }
 
        public IQueryable<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc,
            Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda)
        {
            //是否升序
            if (isAsc)
            {
                return dbContext.Set<T>().Where(WhereLambda).OrderBy(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return dbContext.Set<T>().Where(WhereLambda).OrderByDescending(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }
 
        public bool SaveChanges()
        {
            return dbContext.SaveChanges() > 0;
        }
    }
}

BaseDAL完成后,我們在添加一個類名稱為StaffDAL,繼承自BaseDAL,實現IStaffDAL接口

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.IDAL;
using Company.Model;
 
namespace Company.DAL
{
    public partial class StaffDAL:BaseDAL<Staff>,IStaffDAL
    {
    }
}

StaffDAL完成后,我們要完成的是DALContainer,該類庫主要是創建IDAL的實例對象,我們這里可以自己寫一個工廠也可以通過一些第三方的IOC框架,這里使用Autofac 1.選中DALContainer=>右鍵=>管理Nuget程序包=>搜索Autofac=>下載安裝對應,net版本的AutoFac 2.安裝完成后,我們在DALContainer下添加一個名為Container的類.

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.DAL;
using Company.IDAL;
 
namespace Company.DALContainer
{
    public class Container
    {
        /// <summary>
        /// IOC 容器
        /// </summary>
        public static IContainer container = null;
 
        /// <summary>
        /// 獲取 IDal 的實例化對象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            try
            {
                if (container == null)
                {
                    Initialise();
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("IOC實例化出錯!" + ex.Message);
            }
 
            return container.Resolve<T>();
        }
 
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialise()
        {
            var builder = new ContainerBuilder();
            //格式:builder.RegisterType<xxxx>().As<Ixxxx>().InstancePerLifetimeScope();
            builder.RegisterType<StaffDAL>().As<IStaffDAL>().InstancePerLifetimeScope();
            container = builder.Build();
        }
    }
}

這時候我們數據訪問層已經完成,結構如下

業務邏輯層:

選中Company.IBLL,右鍵=>添加一個接口,名稱為IBaseService,里面也是封裝的一些公用方法

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
 
namespace Company.IBLL
{
    public partial interface IBaseService<T> where T:class ,new()
    {
        bool Add(T t);
        bool Delete(T t);
        bool Update(T t);
        IQueryable<T> GetModels(Expression<Func<T, bool>> whereLambda);
        IQueryable<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc, Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda);
    }
}

IBaseService完成后,我們繼續添加一個接口,名稱為IStaffService,繼承自IBaseService

 

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.Model;
 
namespace Company.IBLL
{
    public partial interface IStaffService : IBaseService<Staff>
    {
    }
}

Company.IBLL,完成后,我們開始完成BLL 選中Company.BLL=>右鍵=>添加一個類,名稱為BaseService,這個類是對IBaseService的具體實現. 這個類需要調用IDAL接口實例的方法,不知道具體調用哪一個IDAL實例,我這里只有一張Staff表,也就只有一個IStaffDAL的實例,但是如果我們這里有很多表的話,就有很多IDAL接口實例,這時我們的基類BaseService不知道調用哪一個,但是繼承它的子類知道. 所以我們這里把BaseService定義成抽象類,寫一個IBaseDAL的屬性,再寫一個抽象方法,該方法的調用寫在 BaseService默認的無參構造函數內,當BaseService創建實例的時候會執行這個抽象方法,然后執行子類重寫它的方法 為IBaseDAL屬性賦一個具體的IDAL實例對象.

 

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Company.IDAL;
 
namespace Company.BLL
{
    public abstract partial class BaseService<T> where T : class, new()
    {
        public BaseService()
        {
            SetDal();
        }
 
        public IBaseDAL<T> Dal{get;set;};
 
        public abstract void SetDal();
        
        public bool Add(T t)
        {
            Dal.Add(t);
            return Dal.SaveChanges();
        }
        public bool Delete(T t)
        {
            Dal.Delete(t);
            return Dal.SaveChanges();
        }
        public bool Update(T t)
        {
            Dal.Update(t);
            return Dal.SaveChanges();
        }
        public IQueryable<T> GetModels(Expression<Func<T, bool>> whereLambda)
        {
            return Dal.GetModels(whereLambda);
        }
 
        public IQueryable<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc,
            Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda)
        {
            return Dal.GetModelsByPage(pageSize, pageIndex, isAsc, OrderByLambda, WhereLambda);
        }
    }
}

基類BaseService完成后,我們去完成子類StaffService,添加一個類名稱為StaffService,繼承BaseService,實現IStaffService,重寫父類的抽象方法,為父類的IBaseDAL屬性賦值

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.IBLL;
using Company.IDAL;
using Company.Model;
 
namespace Company.BLL
{
    public partial class StaffService : BaseService<Staff>, IStaffService
    {
        private IStaffDAL StaffDAL = DALContainer.Container.Resolve<IStaffDAL>();
        public override void SetDal()
        {
            Dal = StaffDAL;
        }
    }
}

子類完成后,我們選中BLLContainer添加一個名為Container的類,添加對Autofac.dll 的引用,該類是創建IBLL的實例

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Company.BLL;
using Company.IBLL;
 
namespace Company.BLLContainer
{
   public class Container
    {
 
        /// <summary>
        /// IOC 容器
        /// </summary>
        public static IContainer container = null;
 
        /// <summary>
        /// 獲取 IDal 的實例化對象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            try
            {
                if (container == null)
                {
                    Initialise();
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("IOC實例化出錯!" + ex.Message);
            }
 
            return container.Resolve<T>();
        }
 
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialise()
        {
            var builder = new ContainerBuilder();
            //格式:builder.RegisterType<xxxx>().As<Ixxxx>().InstancePerLifetimeScope();
            builder.RegisterType<StaffService>().As<IStaffService>().InstancePerLifetimeScope();
            container = builder.Build();
        }
    }
}

業務邏輯層完成0

,

表現層:

添加對EntityFramework.SqlServer.dll 的引用,不然會報錯. 我們這里寫個簡單的增刪改查測試一下,過程就不具體描述了,

視圖:

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

@using Company.Model
@model List<Company.Model.Staff>
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
<div>
    <h1>簡單的畫一個表格展示數據</h1>
    <table border="1" cellpadding="0" cellspacing="0">
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>年齡</th>
            <th>性別</th>
        </tr>
        @foreach (Staff staff in Model)
        {
            <tr>
                <td>@staff.Id</td>
                <td>@staff.Name</td>
                <td>@staff.Age</td>
                <td>@staff.Sex</td>
            </tr>
        }
    </table>
    <hr/>
    <h1>增加</h1>
    <form action="@Url.Action("Add", "Home")" method="POST">
        姓名:<input name="Name"/>
        年齡:<input name="Age"/>
        性別:<input name="Sex"/>
        <button type="submit">提交</button>
    </form>
    <hr/>
    <h1>修改</h1>
    <form action="@Url.Action("update", "Home")" method="POST">
        Id:<input name="Id" />
        姓名:<input name="Name"/>
        年齡:<input name="Age"/>
        性別:<input name="Sex"/>
        <button type="submit">提交</button>
    </form>
    <hr />
    <h1>刪除</h1>
    <form action="@Url.Action("Delete", "Home")" method="POST">
        Id:<input name="Id" />
        <button type="submit">提交</button>
    </form>
</div>
</body>
</html>

控制器:

著作權歸作者所有。
商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
作者:卷貓
鏈接:http://anneke.cn/ArticleInfo/Detial?id=11
來源:Anneke.cn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Company.IBLL;
using Company.Model;
 
namespace Company.UI.Controllers
{
    public class HomeController : Controller
    {
        private IStaffService StaffService = BLLContainer.Container.Resolve<IStaffService>();
        // GET: Home
        public ActionResult Index()
        {
            List<Staff>list = StaffService.GetModels(p => true).ToList();
            return View(list);
        }
        public ActionResult Add(Staff staff)
        {
            if (StaffService.Add(staff))
            {
                return Redirect("Index");
            }
            else
            {
                return Content("no");
            }
        }
        public ActionResult Update(Staff staff)
        {
            if (StaffService.Update(staff))
            {
                return Redirect("Index");
            }
            else
            {
                return Content("no");
            }
        }
        public ActionResult Delete(int Id)
        {
            var staff = StaffService.GetModels(p => p.Id == Id).FirstOrDefault();
            if (StaffService.Delete(staff))
            {
                return Redirect("Index");
            }
            else
            {
                return Content("no");
            }
        }
    }
}


完整Demo https://github.com/zhenzhenkeai/Asp.Net-MVC-EF-Demo

The End


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM