Exploring the wonderful journey of the ASP Mvc5+ef7

Source: Internet
Author: User
Tags hosting

Order

This year Microsoft is very strong, Win10 has attracted the attention of the public, and the latest. NET5 frame is ok.

The latest. NET5 is open source, and is cross-platform with NuGet and node and bower, which means it can be developed directly on Mac or Linux using. Net.

And the latest MVC5 and EF Framework is also a change of face, and the previous Mvc4 of the project is different, if the transplant in addition to the core code can be copied, all the others have to re-come.

Recently prepared to revise the site, so tried a new framework, of course, because now is still preview version of the changes are all super-large, so also took a lot of detours;

Project preparation
    • Tools: Vs2015/visual Studio Code 2015

    • Mvc5 VS Plugins: The latest preview version is Beta7

Because it is BETA7, and Microsoft's official documentation and examples are mostly applicable, but in some places is wrong, such as EF commands, EF Beta3 and Beta7 very different, this is the preview version of the shortcomings, and occasionally changed.
In addition, I use the VS2015 instead of visual Studio Code, after all, there is a better affirmation of good ah.

Start a new project

Open VS, click File-New-project-web

Here is the name: Musicbank, is a music shop bar.

Here we'll have an empty one. Let's build model/ef ourselves ....
OK, after the project is established, we see this.

You can see that our project is actually under the SRC folder. There is nothing in the project other than reference + simple settings.

Environment collocation

The project has, but it is not directly used, we need to build the environment, such as we need to introduce EF and so on.

Dependencies

Open the file "Project.json" we modify the dependencies section to:

"Dependencies" "Microsoft.AspNet.Server.IIS" "1.0.0-beta7" "Microsoft.AspNet.Server.WebListener" "1.0.0-beta7" "Microsoft.AspNet.StaticFiles" "1.0.0-beta7" "MICROSOFT.ASPNET.MVC" "6.0.0-beta7" "Entityframework.commands" "7.0.0-beta7" "Entityframework.sqlserver" "7.0.0-beta7" "Microsoft.Framework.Configuration.Json" "1.0.0-beta7" "Microsoft.Framework.Configuration.UserSecrets" "1.0.0-beta7" },

The dependency on MVC, EF, and configuration is added here.
The role of MVC is mainly used for controller parsing and other operations, including WEBAPI.
EF is, of course, the database.
Configuration is used to read local configurations for easy setup.

Commands

Open the file "Project.json" we modify the commands section to:

"Commands" "Web" "Microsoft.AspNet.Hosting--config Hosting.ini" "EF" "Entityframework.commands" },

The main function of the Commands module is command line execution, which simplifies operations such as " EF" on behalf of "Entityframework.commands" when actually executing.

Model

OK, here we first set up the folder Models, and then we right-add-class on the Model folder:

Artist
using using using using  Public class Artist    {        [Key] public        getset;}         Public string Get set; } public        intgetsetpublicvirtualget  set; }    }}

A singer, with a name and age, and then n a song.

Audio
using using using  Public class Audio    {        [Key] public        getset;}         Public string Get set; } public        intgetset;}         Public string Get set; Public        getsetpublicgetset;}}    }

The song also simplifies, a name, a type, a source file, belongs to a singer.

Musiccontext

This presumably everyone is not unfamiliar with it, for database queries and other operations on this, is the essence of EF.

using  Public class Musiccontext:dbcontext public    getsetpublicgetset;}}    }

Just add two tables here to OK.

SampleData

For convenience, here I do the initialization of the data directly when the database is created, adding some default data.

usingMicrosoft.Framework.DependencyInjection;usingSystem;usingSystem.linq;namespace musicbank.models{ Public classSampleData { Public Static void Initialize(IServiceProvider serviceprovider) {varcontext = serviceprovider.getservice<musiccontext> ();if(Context. Database.ensurecreated ()) {if(!context. Artists.any ()) {varAusten = context. Artists.add (NewArtist {Name ="Austen", age = +}). Entity;varDickens = context. Artists.add (NewArtist {Name ="Dickens", age = -}). Entity;varCervantes = context. Artists.add (NewArtist {Name ="Cervantes", age = -}).                    Entity; Context. Audio.addrange (NewAudio () {Name ="Pride", Type =1, Artist = Austen, SRC ="Pride.mp3"},NewAudio () {Name ="Northanger", Type =2, Artist = Austen, SRC ="Northanger.mp3"},NewAudio () {Name ="David", Type =3, Artist = Dickens, SRC ="David.mp3"},NewAudio () {Name ="Donquixote", Type =1, Artist = cervantes, SRC ="Donquixote.mp3"}                    ); Context.                SaveChanges (); }            }        }    }}

First, this is a static method that needs to pass in a "IServiceProvider", which can be called when the project is started.

After the method has entered we get to the above "Musiccontext", then we do the database creation and data add work.

if (context. Database. ensurecreated())

This sentence is used primarily to determine whether a database creation is required, if it is to be created, return true at the same time, and then we determine whether there is data, if the database table is empty, then we add some default data.

Configuration file Config.json

Add files to the project root: "Config.json" in which the metabase link fields are as follows:

{  "Data{"musicconnection{"ConnectionString" server= (localdb) \ \ Mssqllocaldb;database=musicbank-database; Trusted_connection=true; Multipleactiveresultsets=true "}
Boot Configuration Startup.cs

When the project is started, the relevant methods in Startup.cs are called to initialize the data.

Here are three things we need to do:

    1. Get to Configuration Config.json, complete in constructor
    2. Set the database file connection, complete in the Configureservices method
    3. Initialize database-related data, complete in the Configure method
usingMicrosoft.AspNet.Builder;usingMicrosoft.AspNet.Hosting;usingMicrosoft.Data.Entity;usingMicrosoft.Dnx.Runtime;usingMicrosoft.Framework.Configuration;usingMicrosoft.Framework.DependencyInjection;usingMusicbank.models;namespace musicbank{ Public classStartup { Public Startup(Ihostingenvironment env, iapplicationenvironment appenv) {varBuilder =NewConfigurationbuilder (Appenv.applicationbasepath). Addjsonfile ("Config.json")                . Addjsonfile ($"CONFIG. {env. Environmentname}.json ", Optional:true); Builder.            Addenvironmentvariables (); Configuration = Builder.        Build (); } PublicIconfigurationroot Configuration {Get;Set; } Public void configureservices(Iservicecollection Services) {Services.            Addmvc (); Services. Addentityframework (). Addsqlserver (). adddbcontext<musiccontext> (options = options. Usesqlserver (configuration["Data:MusicConnection:ConnectionString"]);        }); } Public void Configure(Iapplicationbuilder app, Ihostingenvironment env) {app.            Usestaticfiles (); App.            Usemvc (); Sampledata.initialize (app.        ApplicationServices); }    }}

Here our initialization is basically done, and now we have a look at how to access the database data.

Controllers

First add Folder Controllers, right-add-new item in root directory

Here I use a simple webapi to illustrate the data, which will be related to the rendering of the detailed writing data in the article later.

In the file AudioController.cs, we change the code to:

using using using using System.linq;namespace musicbank.controllers{    [Route ("Api/[controller]"Publicclass Audiocontroller:controller    {public        getset;}         Public Get ()        return db. Audio.tolist ();        }        [HttpGet ("{name}"publicGet(string name)        {            return Audio;}}    }

A property, two methods.

Here we can see that the Musiccontext property is not initialized, but the following can be called directly, because we have added a property "[Fromservices]", which means that the server can automatically assign a value to the DB using annotations.

The following two methods return the entire list of music, and return music-related information based on the music name.

Of course, there are "[HttpGet]" properties on all two methods, which specify the request type as Get mode, and of course there are several others, such as "HttpPost" "Httpput" "Httpdelete" and so on.

Run

There are two ways to run here, the way IIS and the Web command line are.

Iis

This way runs directly, vs opens the browser and sets the port.

Web

Do you remember the place where the command line was written? There is a line of this:

"Web" "Microsoft.AspNet.Hosting--config hosting.ini",

Here we start the parameter in the "Hosting.ini" file, we open the Hosting.ini file.

Server=microsoft. AspNet. Server. Weblistener server. URLs=http://localhost:

You can find the URL we visited, run it and then copy the URL to the browser to run it OK.
In case you see such a window, you can see that the dnx is actually called to run the program. And DNX can be cross-platform, which means you can run directly on your Mac.

Effect

You can see that the interface call result of two methods is OK.

Code

The project is complete, the code is packaged, and the address is here:
Musicbank

The relevant code in the blog is focused on:
Https://github.com/qiujuer/BeFoot

========================================================
Qiujuer
Blog: Blog.csdn.net/qiujuer
Website: www.qiujuer.net
Open Source Library: github.com/qiujuer/genius-android
Open Source Library: Github.com/qiujuer/blink
Reprint Please specify source: http://blog.csdn.net/qiujuer/article/details/48268729
--open source of learning, for open source, beginner's mentality, with June mutual encouragement!

========================================================

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Exploring the wonderful journey of the ASP Mvc5+ef7

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.