天天看點

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

架構圖:

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

使用的資料庫:

一張公司的員工資訊表,測試資料

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

解決方案項目設計:

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模闆. 如圖:

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

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

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

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

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

這時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();
        }
    }
}      

這時候我們資料通路層已經完成,結構如下

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

業務邏輯層:

選中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

,

Asp.Net MVC+EF+三層架構的完整搭建過程 架構圖:使用的資料庫:業務邏輯層:表現層:

表現層:

添加對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  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");
            }
        }
    }
}

      

    原文:http://www.cnblogs.com/zzqvq/p/5816091.html