MVC5 + EF6 Complete Introductory tutorial Three

Source: Internet
Author: User

Original: MVC5 + EF6 Complete Introductory tutorial Three

The long-awaited EF is finally here.

By the end of this article, you will have mastered the complete development process based on the EF data model.

The EF data model will be built and used this time.

Based on this model, the previous example is added to the database query validation feature.

article outline

Overview & Essentials

Detailed steps

Summarize

Overview & Essentials

The following is the main point of this article, the body part will be described in detail.

    • EF Frame Composition
    • New EF-Based data Model conventions
    • The important concept of ORM, and the difference between the traditional way of development
    • The overall process of EF development
Detailed Steps
    • Create a new folder and plan your code placement.
    • Create a related class (Data Model)
    • Create Database Context
    • Create initializer, use EF to initialize the database, insert sample data
    • Complete database Query validation
Create a new folder and plan your code placement.
    1. Create a new ViewModels folder under the root directory.

The Models folder contains entities that correspond to database tables.

The data that needs to be displayed in the view and the entity model in the Models do not necessarily correspond, so you need a custom data model specifically for view , which we call ViewModel, placed in VIEWMO Dels folder inside.

    1. Create a new DAL folder under the root directory.

The DAL places data access related classes.

NOTE This article puts AccountContext.cs, AccountInitializer.cs

Create a related class (Data Model)

To get closer to the real situation, we set up three related classes for the user.

Sysuser, Sysrole, Sysuserrole

This is a typical model for user Rights Management RBAC (role–based access Control), and more complex models can be extended on this basis.

OK, let's start with the new model.

We first go online to find a general diagram for reference, open Baidu, enter user role , search for pictures.

Pick a similar reference to do.

NOTE permission is related to the System Management category, does not involve the specific business, I add the SYS prefix when the name, so and fields separated.

Refer to the diagram above to create the Data model

Sysuser Entity

Sysrole Entity

Sysuserrole Entity

For the conventions and descriptions of the above classes:

  1. When EF generates a database, the ID property becomes the primary key. (Convention: EF will default to generate a primary key for ID or Classnameid, MSDN recommends maintaining style consistency, both with ID or Classnameid, we use ID here)
  2. When EF generates a database, the <navigation property name><primary The key property name> this form as a foreign key. Convention

    For example, foreign key Sysuserid = Sysuser (navigation property) +id (primary key of Sysuser)

  3. Several properties defined as virtual are the navigation attribute (virtual must, just the customary usage, and the following article will explain the benefits of using virtual).

    The navigation property holds other associated entity (entities)

    In the example, Sysuser and Sysuserrole are a one-to-many relationship, and Sysrole and Sysuserrole are also a couple of relationships.

    If "Many", the attribute type must be List (ICollection is used here)

Create Database Context

Pre-condition: Install EF

Open Tool à Library Package Manager à Package Manager Console

Input Install-package EntityFramework

Go to MSDN to see the next EF architecture diagram: http://msdn.microsoft.com/en-us/data/aa937709

As you can see, the EF Framework implements database operations at the bottom by calling ADO.

The performance and flexibility of a multi-turn bend will certainly be compromised, so the end of this series will also give Mvc+ado. NET solution, you can choose according to your needs.

NOTE

Microsoft's official ORM Framework includes LINQ to SQL and the Entity Framework.

EF is the latest and recommended framework for use with MVC.

Add some important concepts before the actual operation:

Without an ORM framework, we typically use ADO for database development:

    1. Encapsulates the operation of an ADO database into a class SqlHelper
    2. Call SqlHelper at the DAL layer
    3. Other layers call the DAL for database operations

After using ORM, take the previous sysuser as an example:

O (Object) à the class Sysuser in the program is the object

R (Relation) à tables in the database

M (Mapping) à mapping Relationships of O and R

ORM's improvements to the traditional approach:

Acts as a bridge, realizes the mapping of relational data and object data, and generates SQL statements automatically through mapping.

For commonly used operations, the steps to write SQL statements are saved.

Well, now the necessary concepts should be understood, and we'll do the actual work below.

Create the class AccountContext.cs, let him inherit from the System.Data.Entity.DbContext, we use this class to complete the function of EF.

Here are three main things to do:

  1. Create a dbset for each entity set

    In EF, typically an entity set corresponds to a table in the database, one row in the entity table.

  2. Specify a connection string

    The base ("accountcontext") in the constructor.

    By default, like the class name, which is Accountcontext, we explicitly assign it to him.

  3. Specify a table name in the singular form

    modelbuilder.conventions.remove<pluralizingtablenameconvention> ();

    By default, tables are generated in complex form, such as sysusers

    NOTE table names use a single plural form to see their own habits, there is no clear rules. Some companies table names are used in the singular, some companies according to the meaning of the table, there are singular and plural.

In conjunction with the 2nd above, the connection string in Web. config is specified first.

such as, affixed with the appsettings configuration section above added.

NOTE attachdbfilename=| Datadirectory|\mvcdemo.mdf Sets the location of the database file: Under the App_Data folder in the project root directory.

create initializer, use EF to initialize the database, insert sample data

EF can build databases in a number of ways.

We use the following methods:

The first time you run the program, you create a new database, insert test data, delete the rebuild database when the model changes (and database inconsistency), and insert the test data.

At present, in the development stage, the direct drop and re-create is more convenient without the problem of data loss.

After the end of the series, we will explain how the data modification schema is not lost in the production environment.

Let's do this work by creating a new class AccountInitializer.cs.

The seed method uses the database context (that is, accountcontext) that we defined earlier as a parameter to add entities to the database through this context. (That's what we said in front of the bridge function)

As can be seen from the above code, the seed method for each entity type (we use Sysuser and Sysrole, sysuserrole we do not add):

Create a colletion à add to the appropriate DbSet property à saved to the database.

NOTE You do not have to call the SaveChanges method after each entity group and can be called once after all groups have ended. This is done because if there is an error writing the database code, it is easier to locate the wrong location of the code.

Modify the Web. config to notify EF to use the initializer class we just wrote.

Locate the EntityFramework configuration section and add the contents of the box.

In the context configuration section, the value of type corresponds to (full description of the context class, assembly)

Databaseinitializer configuration section, the value of type corresponds to (full description of initializer class, assembly)

Note : If you do not want EF to use a context, you can set the box below to true.

Complete database Query validation

Now EF everything is ready.

Run the program, and when the database is first connected, EF compares model (ACCOUNTCONTEXT and entity classes) and database. If the two sides are inconsistent, the program will drop and re-create the database.

Because we don't have a database-connected operation yet, EF is not functioning yet.

Now we are done with the previous login function.

    1. let's do a little change, models . à Add an email field inside the SysUser.cs.

      same Dal à AccountInitializer.cs à This field is also added to the sample data in seed

NOTE Add an email is because the previous login page filled in the email value, the following will be input email and password to the database for comparison.

    1. Open Controllers à AccountController.cs
      1. Instantiate a database context object
      2. Modify the login Action of the HttpPost type to query the database for comparison.

NOTE

People who have used SQL know that learning SQL, the most complex is the query, the various inquiries to learn, the basic mastery of more than 70%.

The data manipulation of the EF data model is the same, with emphasis on queries, and the next article expands. (Complex queries from simple queries to conditions, aggregations, joins, etc. are all involved)

Run the login.cshtml page, enter the correct and incorrect login information under authentication.

Also check if the database section meets our expectations:

    1. Open the database and discover that the Mvcdemo database is new and the sample data is already inserted.
    2. Open the project's App_Data folder and discover that the database file already exists.

Summary

OK, so far, we've built the EF framework, initialized the database, and queried a user's information.

It is important to note that the current login function is still relatively simple, not the real sign-in function (for example, the input is also missing validation, the password is not added salt), just to illustrate the use of EF. Based on the series of articles about the needs of knowledge points, will eventually achieve full functionality.

Finally, let's review the focus of this article: Mastering the entire process of using EF development.

Create the data Model à CREATE DATABASE Context à Create Databaseinitializer à Configuring the EntityFramework Context configuration section

I hope we can understand the whole process clearly and understand the function of each process.

Well, this article is here.

You are welcome to ask more questions and comments to make the next article better:)

MVC5 + EF6 Complete Introductory tutorial Three

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.