.Net架構搭建之1、SQL Server EF MVC簡單三層架構

來源:互聯網
上載者:User

標籤:

.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 展示層處理

先簡單修改一下預設路由

建立首頁控制器和頁面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架構項目,關鍵流程和代碼都已貼上,按步驟來應該可以正常運行,如果不能正常運行,可以同我交流,可以加補一些更詳細的步驟。

後續會加上另外幾種架構。

.Net架構搭建之1、SQL Server EF MVC簡單三層架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.