Play to ASP. 5: Initialize Database

Source: Internet
Author: User

1. Initializing the database

    • 1.2 Catalog

This is not a post on the schema /architecture design, but it is structured to explain the article for the purpose of first, but multi-layered.

Cut this diagram is also convenient for you to find the code file path below!

    • 1.2 Code

The console Application is the first to demonstrate. (compared to the egg ache, MS for the ASP. NET 5 test framework is available in version beta1, Xunit.krunner. I don't know what to do with that, Beta2. )

Whether you use EF or not? The traditional approach is to design the database first, but when writing code for object development or to design entities (models), in order to facilitate the mapping of entity properties and database fields is one by one correspondence (can also be configured through the Fluent API , entity attribute design and field does not correspond). Entities can act as business objects, view models, and transport objects. However, depending on your needs, these objects or model properties are not necessarily consistent with database fields and can be defined differently .

We first design a solid base class (or that sentence, only for the explanation, the code is not complete or not rigorous, understand hooray! ):

usingSystem.ComponentModel.DataAnnotations;namespaceblogaspnet5.entity.bases{/// <summary>    ///Entity base class/// </summary>    /// <typeparam name= "T" >primary Key Type</typeparam>     Public classEntitybase<t>{[Key] PublicT Id {Get;Set; } //Record creation Time//whether to delete//line version    }}

Note: EF has an integer and GUID type for the primary key type, its attributes are Id or class name +id (not case sensitive), can not be labeled key, integer self-increment, easy to read, Guid, easy to merge data, or string. So the generics are used here, and then the inheritance determines what type.

The following defines the account-related role entities:

usingBlogASPNET5.Entity.Bases;usingSystem.Collections.Generic;namespaceblogaspnet5.entity.accounts{/// <summary>    ///role Entity/// </summary>     Public classrole:entitybase<int>    {         Public stringName {Get;Set; }  Public stringDescription {Get;Set; } /// <summary>        ///Navigation Properties (do not navigate properties when Redis is shown later)/// </summary>         PublicIcollection<user> Users {Get;Set; } }    }

Account-related user entities:

usingBlogASPNET5.Entity.Bases;namespaceblogaspnet5.entity.accounts{ Public classuser:entitybase<int>    {         Public stringName {Get;Set; }  Public stringPassword {Get;Set; }  PublicGender Gender {Get;Set; } /// <summary>        ///role ID FOREIGN key/// </summary>         Public intRoleid {Get;Set; } /// <summary>        ///Navigation Properties/// </summary>         PublicRole role {Get;Set; } }    /// <summary>    ///Gender enumeration Type/// </summary>     Public enumGender {man, woman}}

Note: EF7 does not support complex types (which can actually be inherited), but enumeration types support retention, and with Redislater, navigation properties are useless.

Now that you want to use EF to create the database and initialize the data, you need the EF action Context class :

usingBlogASPNET5.Entity.Accounts;usingMicrosoft.Data.Entity;usingMicrosoft.Data.Entity.Metadata;namespaceblogaspnet5.repository.contexts{ Public classEfcontext:D Bcontext { PublicDbset<role> Roles {Get;Set; }  PublicDbset<user> Users {Get;Set; } protected Override voidonconfiguring (dbcontextoptions options) {options. Usesqlserver ("server=.;D Atabase=testdb; Uid=sa; pwd=123456;"); }        protected Override voidonmodelcreating (ModelBuilder ModelBuilder) {//Many-to-one relationships and specifying foreign keysModelbuilder.entity<user> (). Manytoone (r = r.role, U = u.users). ForeignKey (f =F.roleid); }    }}

Define the Initialize database method:

usingBlogASPNET5.Entity.Accounts;usingBlogASPNET5.Repository.Contexts;usingSystem.Linq;namespaceblogaspnet5.repository.migrations{ Public Static classSampleData {StaticEfcontext db =NewEfcontext ();  Public Static voidSetData () {db.            Database.ensuredeleted (); Db.            Database.ensurecreated (); Db. ADD (NewRole {Name ="Manage", Description ="Administrator" },                NewRole {Name ="member", Description ="member" }); Db.            SaveChanges (); //Well , eggs, coreclr, no random function, no loops.             for(inti =1; I <= +; i++) {db. ADD (NewUser {Name="Admin"+I, Password="ABC"+I, Gender=Gender.man, Role= db. Roles.single (r = R.name = ="Manage")                    }); Db.            SaveChanges (); }             for(inti =1; I <= +; i++) {db. ADD (NewUser {Name="member"+I, Password="EFG"+I, Gender=Gender.woman, Role= db. Roles.single (r = R.name = ="member")                    }); Db.            SaveChanges (); }        }    }}
    • 1.3 Calls

In the console program call:

Using blogaspnet5.repository.contexts;using blogaspnet5.repository.migrations;using System;namespace blogaspnet5.consoleapp{Public    Class program    {public        void Main (string[] args)        {            //Initialize data, Create the comment out                 sampledata.setdata ();            Console.WriteLine ("Set Data ok!");            Console.ReadLine ();            using (var db = new Efcontext ())            {                var lists = db. Users;                foreach (var item in lists)                {                    Console.WriteLine (item. Name);                }            }            Console.ReadLine ();}}}    

The result is not. EF7 Beta2 Another improvement: the created table, no longer have the migrationhistory(look uncomfortable) this table.

2. Summary

This article first initializes the database, the next chapter data operation encapsulation and query paging.

Make a "small advertisement"! Welcome to like-minded park friends, join QQ Group:290576772(Overtime Annotated Blog Park)

Play to ASP. 5: Initialize Database

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.