Recently, as the project draws to a close, I feel it is necessary to share my "Patchwork" Web application development model based on ASP.net MVC 3. By the way, let's make a summary of this project.
Keywords:Razor, easyui, entityframework, T4, LINQ to entity, JSON
1)Razor: ASP. NET mvc3 introduces a new view engine.
2)Easyui: A jquery-based UI framework
3)Entityframework:Microsoft's database relationship ing framework
4)T4:Template syntax generated by the Code. The add controller and add view dialog box in MVC executes the code generation using the T4 template behind the scenes.
First:
In this figure, the left-side menu bar is dynamically generated through the database configuration and linked to permissions. The permission granularity is controlled to the button level to grant a role the permission to add or delete a record.
All the headers in the list in the figure are automatically generated. The device details page is generated by modifying the details of mvc3.
This editing interface is also automatically generated by the T4 template. Even include the Chinese label (extracted from the field comments in powerdesigner), including the drop-down list and date selection box, which are automatically added based on the judgment database type.
1. Use powerdesigner to build a data model
In entityframework, there are two development modes: code first and common database and then development. This project uses the latter.
I am used to building a conceptual model directly. After the initial requirements are finalized, I will add details to the physical model. During this period, it is very important to add comments to each field, later, you need to generate text on the Interface Based on these Chinese annotations. I used an automatic modification script in powerdesigner to convert name to commet
Option ExplicitValidationMode = TrueInteractiveMode = im_BatchDim mdl 'the current model'get the current active modelSet mdl = ActiveModelIf (mdl Is Nothing) ThenMsgBox "There is no current Model"ElseIf Not mdl.IsKindOf(PdPDM.cls_Model) ThenMsgBox "The current model is not an Physical Data model."ElseProcessFolder mdlEnd If'This routine copy name into code for each table, each column and each view'of the current folderPrivate sub ProcessFolder(folder)Dim Tab 'running tablefor each Tab in folder.tablesif not Tab.isShortcut thenif Tab.Comment ="" thenTab.Comment = tab.nameelseTab.comment=Tab.name &"," &Tab.commentEnd ifDim col 'running columnfor each col in tab.columnsif col.comment ="" thencol.comment= col.nameelsecol.comment=col.name & "," &col.commentend ifnextend ifnextDim view 'running viewfor each view in folder.Viewsif not view.isShortcut thenview.comment = view.nameend ifnext'go into the sub-packagesDim f 'running folderFor Each f In folder.Packagesif not f.IsShortcut thenProcessFolder fend ifNextend sub
Thumbnail of the physical model of this project.
When designing a databaseData Field redundancy and simplified processing logicThe trade-off between them is the most critical. The most common is the inheritance and combination of objects in the business domain. For example, some types of devices have special information, and most of the device fields are common. In this case, we should consider whether to put multiple tables or tables with multiple redundant fields, in this case, a parent table "device" (including all fields common to the device) and multiple types of sub-tables (storing special fields) are used to reduce field redundancy, improve system scalability. Of course, this is designed for the special nature of this project, and the types of equipment will not change significantly.
It is also necessary to set some public tables. In this case, a public photo table contains
In this way, you can add photos to any information table. The data table record number in the information table stores the primary key ID of a table, and the table number stores the corresponding information table.
After the database is designed, powerdesigner is used to directly generate the database. This project uses SQL Server 2008, because entityframework currently only supports Microsoft.
During database generation, if your SQL Server is above 2005, you must solve the following problems:
Powerdesigner 16 generate datebase for sql2005 cannot find the sysproperties table problem 2. Add Entity Framework support to the Project
Suppose you have installed mvc3 in vs2010.
There are only two projects in the solution: domain and webui. As the name suggests, domain involves domain model-related data access, which is also generated by entityframework in this project.Entity Data Model, Where the controller and view are stored in webui.
The edmx file in the figure is our object data model. You can right-click the file and add or refresh the database to update the current object model and match the database.
When you press the save key, Microsoft's awesome T4 template quietly generates a large number of entity classes for you in the background. You can expand the edmx file to view them:
It is probably a structure like this: context and entity, in which context inherits from objectcontext. You can regard it as the data access layer in the three-tier architecture, and the entity class is the entity layer in the three-tier architecture.
If you want to go deep into this automatic generation process, such as modifying the generated object name, you can modify the edmx Attribute-custom tool. But I think it is too painful, so keep the default generation method:Entitymodelcodegenerator, resultAll my object classes are named with the T _ prefix (all tables in my database start with T ).
Now, your data preparation is complete. Note that you do not need to write an SQL statement. In addition, any changes to the database in the future will be automatically synchronized to your project as you right-click on the edmx file, and everything will be cool, comfortable, and natural.
3. Modify the T4 Template
This is the most critical step. It seems to be a little technical compared to other steps in the project. Because you have to understand the T4 template syntax, you have to write a complete add, delete, and modify page in advance (the page content includes razor syntax, easyui, Ajax, and other technologies ).
However, after this step is completed, your project will complete 70% of the work. Yes, that's right! More than half done!
First, let's take a look at the T4 syntax. If your vs is the default path, spicy, you can find templates with very bad syntax in this path (because there is no intelligent editor capable of editing them so far, you can only hand-Write it by feeling)
C: \ Program Files \ Microsoft Visual Studio 10.0 \ common7 \ ide \ itemtemplates \ CSHARP \ WEB \ MVC 3 \ codetemplates
Here, addcontroller is the template you run when you right-click the Controller in Vs and addview is the template executed when you add the view. Why modify them? Because we want to add jquery, easyui, JSON, and better page experience and asynchronous processing.
There are two files in the addcontroller Folder:Controllerwithcontext. tt,Download will be provided below. The content will not be described in detail. Let's take two examples. After you download them in detail, we will discuss: (The cnblogs editor does not have T4 syntax coloring. I can barely read it)
public JsonResult List(int page,int rows) { var q = from e in db.<#= entitySetName #> orderby e.<#=primaryKey.Name#> select new {<#int i=0; foreach (ModelProperty property in GetModelProperties(Model.ModelType)) {#> <#=property.Name #> = e.<#=property.Name #><#if(i!=GetModelProperties(Model.ModelType).Count-1){#>,<#}#> <# i++; }#> }; var result = q.Skip((page - 1)*rows).Take(rows).ToList(); Dictionary<string, object> json = new Dictionary<string, object>(); json.Add("total", q.ToList().Count); json.Add("rows", result); return Json(json, JsonRequestBehavior.AllowGet); }
The above method adds a list method for the Controller to return jsonresult. As we all know, database table operations are nothing more than adding, deleting, modifying, and querying. This list is used to support the list. Parameter pages and rows are used to support grid pages of easyui.
[HttpPost] public JsonResult Create(<#= modelName #> <#= modelVariable #>) { JsonResult json=new JsonResult(); json.Data=true; try{<# if(isObjectContext) { #> db.<#= entitySetName #>.AddObject(<#= modelVariable #>);<# } else { #> db.<#= entitySetName #>.Add(<#= modelVariable #>);<# } #> db.SaveChanges(); } catch(Exception ee) { json.Data=ee.Message; } return json; }
Create is to support the creation. Returns true in JSON format.
In this project, many controller httppost Methods return jsonresult. There are two purposes:
I. To support easyui;
2. Another client in this project is the Android tablet. The Controller acts as a remote data source and provides JSON format data to applications on the tablet.
For more information about the T4 template, see here.
Well, write it here first. Return immediately.
Download a custom template.