. NET Framework build 1, SQL Server EF MVC simple three-tier framework

Source: Internet
Author: User

. NET simple three-tier framework introduction

The simple three-layer framework, which is the most basic framework in. NET development, consists of a data access layer, a logical processing layer, and a presentation layer. In general, the data model layer in the project is also a separate layer, but only a simple data model is not counted in the Business layer division.
Well, frame building, if not understand, may find it difficult to start, understand, naturally know how to do, just one of the steps, compared to the simple function development, is a lot of tedious, the following we come step by step to build their own framework, here only the important steps, other details can be explored without reference.

Model layer creation of data models

Data Model layer, you first create the database and then generate the EF model from the database.

Create a database, table, add a test data

Create a new class library, add an Entity Data model, connect to a database, get a table structure to a solid model

First, add the class library, name: Example.model
Then add the Entity Data Model:



At this point, the model data layer is finished.

Dal Data Access Layer creation

Since we know that there are several layers, so first all of the class Library project first set up, the Web is the empty project of MVC, as for each layer of code, divided into layers to deal with

With EF, to make it easy to use the EF extension, add an expansion pack with NuGet first
entityframework.extended, the version uses the default on the line.

Once added, you can add a Basedal class to facilitate the operation of the DAL layer.

BaseDAL.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Linq.Expressions;usingSystem.Text;usingSystem.Threading.Tasks;usingEntityframework.extensions;usingExample.model;namespace example.dal{ Public classBasedal<t>whereT:class{PrivateExampleentities _db =NULL; PublicExampleentities DB {Get{if(_db = =NULL) _db =NewExampleentities ();return_db; }        } Public VirtualIqueryable<t> Entities {Get{returnDb. Set<t> (). Asnotracking (); }        } Public VirtualIqueryable<t> Table {Get{returnDb. Set<t> (); }        } PublicIlist<t>GetAll(Expression<func<t,BOOL>> exp) {varquery = db. Set<t> (). Where (exp).            Asnotracking (); ilist<t> data = query. ToList ();returnData } 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);                returnDb.            SaveChanges (); }Catch(System.Data.Entity.Validation.DbEntityValidationException ex) {stringErrMsg ="";foreach(varIteminchEx. Entityvalidationerrors.first (). Validationerrors) {errmsg + = Item. ErrorMessage +" ; "; }Throw NewException (errmsg); }finally{            }        }//   <summary>         ///   Bulk Add        //   </summary>         ///   <param name= "models" ></param>         ///   <returns></returns>          Public int Addcollect(List<t> models) {Try{foreach(T modelinchModels) {EntityState state = db. Entry (model). State;if(state = = entitystate.detached) {db. Entry (model).                    state = entitystate.added; }                }//db. Set<t> (). ADD (model);                returnDb.            SaveChanges (); }Catch(System.Data.Entity.Validation.DbEntityValidationException ex) {stringErrMsg ="";foreach(varIteminchEx. Entityvalidationerrors.first (). Validationerrors) {errmsg + = Item. ErrorMessage +" ; "; }Throw NewException (errmsg); }finally{            }        } Public int Edit(T model) {Try{Try{db. Set<t> ().                Attach (model); }Catch{} db. Entry (model). state = entitystate.modified;returnDb.            SaveChanges (); }Catch(System.Data.Entity.Validation.DbEntityValidationException ex) {stringErrMsg ="";foreach(varIteminchEx. Entityvalidationerrors.first (). Validationerrors) {errmsg + = Item. ErrorMessage +" ; "; }Throw NewException (errmsg); }finally{            }        }//   <summary>         ///   Batch modification        //   </summary>         ///   <param name= "models" ></param>         ///   <returns></returns>          Public int Editcollect(List<t> models) {Try{foreach(T modelinchModels) {Try{EntityState state = db. Entry (model).                        State; Db. Set<t> ().                    Attach (model); }Catch{} db. Entry (model).                state = entitystate.modified; }returnDb.            SaveChanges (); }Catch(System.Data.Entity.Validation.DbEntityValidationException ex) {stringErrMsg ="";foreach(varIteminchEx. Entityvalidationerrors.first (). Validationerrors) {errmsg + = Item. ErrorMessage +" ; "; }Throw NewException (errmsg); }finally{            }        }//   <summary>         ///   Modify the operation, can only update some columns, high efficiency        //   </summary>           /// <param name= "Funwhere" > query criteria-predicate expression </param>           /// <param name= "Funupdate" > entities-predicate expressions </param>         ///   <returns> number of rows affected by Operation </returns>          Public Virtual int Edit(Expression<func<t,BOOL>> Funwhere, expression<func<t, t>> funupdate) {returnEntities.where (Funwhere).        Update (funupdate); } Public int Delete(T model) {Try{db. configuration.autodetectchangesenabled =false; Db. Entry (model).                state = entitystate.deleted; Db. configuration.autodetectchangesenabled =true;returnDb.            SaveChanges (); }Catch(System.Data.Entity.Validation.DbEntityValidationException ex) {stringErrMsg ="";foreach(varIteminchEx. Entityvalidationerrors.first (). Validationerrors) {errmsg + = Item. ErrorMessage +" ; "; }Throw NewException (errmsg); }finally{            }        } Public int Deleteexp(Expression<func<t,BOOL>> exp) {Try{varQ = db. Set<t> ().                Where (exp); Db. configuration.autodetectchangesenabled =false; Db. Set<t> ().                RemoveRange (q); Db. configuration.autodetectchangesenabled =true;returnDb.            SaveChanges (); }Catch(System.Data.Entity.Validation.DbEntityValidationException ex) {stringErrMsg ="";foreach(varIteminchEx. Entityvalidationerrors.first (). Validationerrors) {errmsg + = Item. ErrorMessage +" ; "; }Throw NewException (errmsg); }finally{            }        }    }}

With the Basedal class, we're going to set up a table-specific SysUserDAL.cs

SysUserDAL.cs
Very simply, let's write a method to read a test data that was previously added to the database

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.Entity;namespace Example.DAL{    publicclass SysUserDAL : BaseDAL<SysUser>    {        publicGetUserById(int id)        {            return Entities.Where(o => o.Id == id).FirstOrDefault();        }    }}
BLL Logic processing Layer Creation

In the EXAMPLE.BLL project, add the Example.BLL.cs

Example.BLL.cs

usingExample.dal;usingExample.model;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.threading.tasks;namespace example.bll{ Public classSYSUSERBLL {PrivateSysuserdal _dal =NULL; PublicSysuserdal Dal {Get{if(_dal = =NULL) _dal =NewSysuserdal ();return_dal; }        } PublicSysuserGetuserbyid(intID) {returnDal.        Getuserbyid (ID); }    }}

The BLL layer content is finished.

The BLL layer is so simple, if you do not make data judgment, call the DAL layer method directly.

MVC WEB Presentation Layer Processing

Simply modify the default route first

Create a Home Controller and page Razor view

Modify the action to index method in the index controller

        privatenull;        public SysUserBLL BLL        {            get            {                ifnullnew SysUserBLL();                return _BLL;            }        }        //        // GET: /Index/        publicIndex()        {            ViewBag.FirstUser = BLL.GetUserById(1);            return View();        }

index.cshtml changes to the page display

@{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>Name: @ (Model!=null?model. UserName: "Empty")</div></body></html>

Operating effect:

This article step by step Introduction If you build a simple three-layer EF MVC Framework Project, the key processes and code are posted, according to the steps should be able to run normally, if not working properly, you can communicate with me, you can add some more detailed steps.

Several additional frameworks are added to the follow-up.

. NET Framework build 1, SQL Server EF MVC simple three-tier framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.