ASP.NETMVC three floor to build a complete project

Source: Internet
Author: User
Tags button type instance method

Next, build a complete project with ASP. NET MVC layer Three:

Architecture diagram:

Database to use:

A company's employee information sheet, test data

Solution Project Design:

1. Create a new blank solution named Company

2. Under this solution, the new Solution folder (Ui,bll,dal,model) can of course add common

3. Create a Class library project under the Bll,dal,model solution folder, respectively

(1). BLL solution folder: COMPANY.BLL, COMPANY.IBLL, Company.bllcontainer

(2). DAL solution folder: Company.dal, Company.idal, Company.dalcontainer

(3). Model Solution Folder: Company.model

4. Under the UI solution folder, add an ASP. NET Web application named Company.ui, and choose our MVC template. :

Model layer: Select Company.model, right-click = + Add = new Item + + add an ADO Entity Data Model name for Company=> Select EF Designer from database and new connection = Select our company database to fill in the appropriate content

Select our staff table and complete the following:


The model layer is now complete. Our database connection string and the EF configuration are in App. config, but our project is running the Web application on our UI layer, so we're going to copy the configuration in app. Config to the UI layer in Web. config Data access layer: Because each entity needs to be censored, we encapsulate a base class here. Select Company.idal, right-click + Add a name called Ibasedal interface and write down the common method signature

 1 copyright belongs to the author. 2 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 3 Roll Cat 4 Modify by: Bird's Nest 5 time:2017-4-2 6 Nest job: http://yipin361.com 7 Link: http://anneke.cn/ArticleInfo/Detial?id=11 8来 Source: anneke.cn 9 Ten using system;11 using system.collections.generic;12 using system.linq;13 using system.linq.expressions;14 using System.text;15 using system.threading.tasks;16 namespace company.idal18 {public partial interface Ibasedal<t         > Where T:class, New () {$ void Add (T t); void Delete (T t); + void Update (T t); 24 Iqueryable<t> getmodels (expression<func<t, bool>> wherelambda); iqueryable<t> GetMo delsbypage<type> (int pageSize, int pageIndex, bool isasc, expression<func<t, type>> Orderbylambda, Expression<func<t, bool>> Wherelambda);//<summary>27///a business may involve operations on multiple tables, you can data, marking the corresponding tag, and finally call the method, the data is submitted to the database one time, avoiding the multiple link database. ///</summary>29 bool SaveChanges (); 30}31} 

The base class interface is encapsulated. Then check company.idal, right-click + Add a name called Istaffdal interface + = Inherit from base class interface

Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source. Roll Cat Modification by: Bird's Nest time:2017-4-2 Nest job: http://yipin361.com Link: http://anneke.cn/ArticleInfo/Detial?id=11 Source: anneke.cnusing 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 complete, Next is the DAL check company.dal=> right-click + Add a class with the name: Basedal, this class is our implementation of the Ibasedal specific, we need to use the EF context object, So adding references to EntityFramework.dll and EntityFramework.SqlServer.dll (which are different references to the EF6 version of the DLL may also be different) it says here that we're going to use the EF object above, and we can't just be new here, Because this can result in data clutter, the EF context object is guaranteed to be unique within the thread. We checked the company.dal=> right-click = To add a class. The name is dbcontextfactory. This class is the only one that creates an EF context object.

 1 Copyright belongs to the author. 2 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 3 Roll Cat 4 Modify by: Bird's Nest 5 time:2017-4-2 6 Nest job: http://yipin361.com 7 Link: http://anneke.cn/ArticleInfo/Detial?id=11 8来 Source: anneke.cn 9 Ten using system;11 using system.collections.generic;12 using system.data.entity;13 using system.linq;14 using System.runtime.remoting.messaging;15 using system.text;16 using system.threading.tasks;17 using Company.Model;18 19 namespace Company.dal20 {public partial class DbContextFactory22 {//<summary>24// Create an EF context object that already exists on the direct fetch, does not exist, and guarantees that the line range is unique.  //</summary>26 public static DbContext Create () {DbContext DbContext = CallContext.GetData ("DbContext") as dbcontext;29 if (dbcontext==null) {Dbcon Text=new companyentities (); Callcontext.setdata ("DbContext", DbContext);}34 re Turn dbcontext;35}36}37} 

EF Context object creation Factory completed, and we are here to complete our Basedal

 1 copyright belongs to the author. 2 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 3 Roll Cat 4 Modify by: Bird's Nest 5 time:2017-4-2 6 Nest job: http://yipin361.com 7 Link: http://anneke.cn/ArticleInfo/Detial?id=11 8来 Source: anneke.cn 9 Ten using system;11 using system.collections.generic;12 using system.data.entity;13 using System.Data.Entity.Migrations ; using system.linq;15 using system.text;16 using system.threading.tasks;17 using company.idal;18 using System.linq.expressions;19 namespace Company.dal21 {public partial class basedal<t> where T:class, new (             ) DbContext DbContext = Dbcontextfactory.create (); public void Add (T t) 26 {27 Dbcontext.set<t> (). ADD (t),}29 public void Delete (T t), {dbcontext.set<t> (). Remove (t),}33 public void Update (T t), dbcontext.set<t> (). AddOrUpdate (t); Panax Notoginseng}38 the public iqueryable<t> getmodels (expression<func<t, Bool>> WHERELAMBDA) (dbcontext.set<t>). Where (WHERELAMBDA);}43 iqueryable<t> getmodelsbypage<type> (int pageSize, int pag Eindex, bool isasc,45 expression<func<t, type>> orderbylambda, Expression<func<t, BOOL&GT;&G T WHERELAMBDA) 46 {47//whether the ascending-if (ISASC) is the dbContext. Set<t> (). Where (WHERELAMBDA). (ORDERBYLAMBDA). Skip ((pageIndex-1) * pageSize). Take (pageSize), Wuyi}52 else53 {dbcontext.set<t> (). Where (WHERELAMBDA). OrderByDescending (ORDERBYLAMBDA). Skip ((pageIndex-1) * pageSize). Take (pageSize),}56}57, Dbcon, public bool SaveChanges () Text. SaveChanges () > 0;61}62}63}

When the Basedal is complete, we add a class name of Staffdal, which inherits from Basedal, implements the Istaffdal interface

1 copyright belongs to the author. 2 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 3 Roll Cat 4 Modify by: Bird's Nest 5 time:2017-4-2 6 Nest job: http://yipin361.com 7 Link: http://anneke.cn/ArticleInfo/Detial?id=11 8来 Source: anneke.cn 9 Ten using system;11 using system.collections.generic;12 using system.linq;13 using system.text;14 using System.threading.tasks;15 using company.idal;16 using company.model;17  namespace company.dal19 {public     Partial class Staffdal:basedal<staff>,istaffdal21     {     }23}

Staffdal finished, we are going to complete the Dalcontainer, the class library is mainly to create Idal instance object, we can write our own factory here can also be through some third-party IOC framework, where AUTOFAC 1 is used. Select Dalcontainer= > right + manage NuGet packages = search autofac=> download installs corresponding, net version of AUTOFAC 2. After the installation is complete, we add a class named Container under Dalcontainer. ( modified: IOC is an injection mode, small series here to continue to introduce a, spring.net Dependency injection mode, this requires a lot of configuration files, but the use of more convenient, skilled after the good! )

 1 Nest want to make some friends in this respect, jkxx123321 2 Another, Bird's Nest want to go to the Internet company, ask a friend introduction, two months, see on my give me the following comments can, now:2017-4-2! 3 rights are vested in the author. 4 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 5 Roll Cat 6 Modify by: Bird's Nest 7 Time:2017-4-2 8 Nest Job: http://yipin361.com 9 Link: http://anneke.cn/ArticleInfo/Detial?id=1110 Source: Anneke.cn11 using autofac;13 using system;14 using system.collections.generic;15 using system.linq;16 using System. Text;17 using system.threading.tasks;18 using company.dal;19 using Company.idal;20 namespace Company.dalcontainer22 {         The public class Container24 {//<summary>26//IOC container///&LT;/SUMMARY&GT;28         public static IContainer container = null;29//<summary>31//Get Idal instantiated object 32 &LT;/SUMMARY&GT;33//<typeparam name= "T" ></typeparam>34//<returns></return s>35 public static T resolve<t> () [try38]     Tainer = = null) 40 {41                Initialise ();}43}44 catch (System.Exception ex) 45 {System.Exception throw new ("IOC instantiation Error!" + ex. Message),}48 return container.         Resolve<t> ();}51//<summary>53///</summary>55 public static void Initialise () () () (), * * * var builder = new Containerbuilder (); 58//Format: Buil Der. Registertype<xxxx> (). As<ixxxx> (). Instanceperlifetimescope (); Registertype<staffdal> (). As<istaffdal> (). Instanceperlifetimescope (); container = Builder. Build (); 61}62}63}

At this point our data access layer has been completed and the structure is as follows

Business Logic Layer:

Check COMPANY.IBLL, right-click + Add an interface, name Ibaseservice, inside is also some common methods of encapsulation

1 Nest want to make some friends in this respect, jkxx123321 2 Another, Bird's Nest want to go to the Internet company, ask a friend introduction, two months, see on my give me the following comments can, now:2017-4-2! 3 copyright belongs to the author. 4 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 5 Roll Cat 6 Links: http://anneke.cn/ArticleInfo/Detial?id=11 7来 Source: anneke.cn 8  9 using system;10 using System.collections.generic;11 using system.linq;12 using system.linq.expressions;13 using system.text;14 using System.threading.tasks;15  namespace Company.ibll17 {public     partial interface ibaseservice<t> where T:class, new (), {+ bool Add (T t); bool Delete (T t); +         bool Update (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);     }26}

After the Ibaseservice is complete, we continue to add an interface named Istaffservice, inherited from Ibaseservice

1 Nest want to make some friends in this respect, jkxx123321 2 Another, Bird's Nest want to go to the Internet company, ask a friend introduction, two months, see on my give me the following comments can, now:2017-4-2! 3 rights are vested in the author. 4 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 5 Roll Cat 6 Modify by: Bird's Nest 7 Time:2017-4-2 8 Nest Job: http://yipin361.com 9 Link: http://anneke.cn/ArticleInfo/Detial?id=1110 Source: Anneke.cn11 using system;13 using system.collections.generic;14 using system.linq;15 using system.text;16 using Sys Tem. Threading.tasks;17 using company.model;18  namespace Company.ibll20 {public     partial interface istaffservice:ibaseservice<staff>22     {     }24}

COMPANY.IBLL, when we finish, we start to complete the BLL. Select Company.bll=> Right-click and add a class named Baseservice, which is a concrete implementation of ibaseservice. This class needs to call the Idal interface instance method, do not know the specific invocation of which Idal instance, I have only one staff table, there is only one istaffdal instance, but if we have many tables here, there are many Idal interface instances, At this point our base class Baseservice does not know which one to call, but the subclass that inherits it knows. So here we define Baseservice as an abstract class, write a Ibasedal property, write an abstract method, the invocation of the method is written in the Baseservice default parameterless constructor, and when Baseservice creates an instance, it executes the abstract method. It then executes a subclass that overrides its method to assign a specific Idal instance object to the Ibasedal property.

Bird's Nest want to make some friends in this respect, jkxx123321 another, Bird's Nest want to go to Internet company, ask a friend introduction, within two months, see on my the following comment on me can, now:2017-4-2! The right to make is owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source. Roll Cat Modification by: Bird's Nest time:2017-4-2 Nest job: http://yipin361.com Link: http://anneke.cn/ArticleInfo/Detial?id=11 Source: anneke.cnusing 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 Bas        EService () {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, EXP Ression<func<t, type>> Orderbylambda, expression<func<t, bool>> WhereLambda) {R        Eturn dal.getmodelsbypage (pageSize, PageIndex, ISASC, Orderbylambda, WHERELAMBDA); }    }}

After the base class Baseservice is finished, we go through the subclass Staffservice, add a class name of Staffservice, inherit Baseservice, implement Istaffservice, override the abstract method of the parent class, Assigning a value to the Ibasedal property of a parent class

1 Nest want to make some friends in this respect, jkxx123321 2 Another, Bird's Nest want to go to the Internet company, ask a friend introduction, two months, see on my give me the following comments can, now:2017-4-2! 3 rights are vested in the author. 4 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 5 Roll Cat 6 Modify by: Bird's Nest 7 Time:2017-4-2 8 Nest Job: http://yipin361.com 9 Link: http://anneke.cn/ArticleInfo/Detial?id=1110 Source: Anneke.cn11 using system;13 using system.collections.generic;14 using system.linq;15 using system.text;16 using Sys Tem. Threading.tasks;17 using company.ibll;18 using company.idal;19 using company.model;20  namespace Company.bll22 { % public     partial class Staffservice:baseservice<staff>, IStaffService24     {         private istaffdal Staffdal = dalcontainer.container.resolve<istaffdal> (); n public         override void Setdal () (         Dal)             = staffdal;29         }30     }31}

When the subclass is complete, we select Bllcontainer to add a class named container, adding a reference to Autofac.dll, which is an instance of creating IBLL

 1 Nest want to make some friends in this respect, jkxx123321 2 Another, Bird's Nest want to go to the Internet company, ask a friend introduction, two months, see on my give me the following comments can, now:2017-4-2! 3 rights are vested in the author. 4 Commercial Reprint please contact the author for authorization, non-commercial reprint please specify the source. 5 Roll Cat 6 Modify by: Bird's Nest 7 Time:2017-4-2 8 Nest Job: http://yipin361.com 9 Link: http://anneke.cn/ArticleInfo/Detial?id=1110 Source: Anneke.cn11 using autofac;13 using system;14 using system.collections.generic;15 using system.linq;16 using System. Text;17 using system.threading.tasks;18 using company.bll;19 using Company.ibll;20 namespace Company.bllcontainer22 { $ public Class Container24 {//<summary>27//IOC container///</summary>         public static IContainer container = null;30//<summary>32///Get Idal Instantiation Object 33 &LT;/SUMMARY&GT;34//<typeparam name= "T" ></typeparam>35//<returns></ret urns>36 public static T resolve<t> () Notoginseng {try39 {max if (  container = = null) 41 {42                   Initialise ();}44}45 catch (System.Exception ex) 46 {$ throw new System.Exception ("IOC instantiation Error!" + ex. Message);}49 return container.         Resolve<t> ();}52//<summary>54///</summary>56 public static void Initialise () $ {$ var builder = new Containerbuilder (); 59//Format: Buil Der. Registertype<xxxx> (). As<ixxxx> (). Instanceperlifetimescope (); Registertype<staffservice> (). As<istaffservice> (). Instanceperlifetimescope (); container = Builder. Build (); 62}63}64}

Business Logic Layer Complete 0

,

Presentation layer:

Add a reference to the EntityFramework.SqlServer.dll, or you will get an error. Here we write a simple to delete and change the test, the process is not specifically described,

View:
 1 @using Company.model 2 @model list<company.model.staff> 3 @{4 Layout = null; 5} 6 <! DOCTYPE html> 7 

Controller:

( Delete method can be improved, we can actively optimize!) Another: What is the best way to write a DAL layer query??? Who offers some good ways to enlighten you! )

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using SYSTEM.WEB.MVC; 6 using COMPANY.IBLL; 7 using Company.model; 8 9 Namespace Company.UI.Controllers10 {One public class Homecontroller:controller12 {private Istaff Service Staffservice = bllcontainer.container.resolve<istaffservice> ();//GET:HOME15 public Acti Onresult Index (), {list<staff>list = staffservice.getmodels (p = = true).             ToList (); return View (list),}20 public ActionResult ADD (staff staff) 21 {22             if (Staffservice.add (staff)) at the Redirect ("Index"), 25}26 Else27 {("no"),}30}31 public ActionResult Update (staff staff) (Staffservice.update) + (staff) IRect ("Index"),}37 else38 {"No"), 40}4 1}42 public actionresult Delete (int Id) p {$ var staff = staffservice.getmodels (p. =& Gt P.id = = Id). FirstOrDefault (), staffservice.delete if (staff), ("staff)", "Redirect" ("Index")      }49 Else50 {("no"), 52}53}54 }55}

ASP.NETMVC three floor to build a complete project

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.