Preface
This year Microsoft is very strong, Win10 has attracted the attention of the public, and the latest. The NET5 frame is OK.
The latest. NET5 is open source and cross-platform using NuGet and node and bower, which means that it can be developed directly on Mac or Linux using. Net.
And the latest MVC5 and EF Framework is also a change in the face, and the previous MVC4 projects are not the same, if the transplant in addition to the core code can be copied, all the others will be back.
Recently prepared to change the site, so tried a new frame; Of course, because now or preview version so changes are very large, so also walked a lot of detours; special here to record. Project Preparation
Tools: vs2015/visual Studio Code 2015 download address
MVC5 VS Plugin: Latest preview for Beta7 download address
Because it is BETA7, and Microsoft official documentation and examples of the most applicable, but some places are not correct, such as the EF command, EF Beta3 and Beta7 difference is very large, this is the preview version of the shortcomings, and occasionally changes.
In addition, I am using the VS2015 instead of visual Studio Code, after all, there is a good point definitely with the AH. Start New Project
Open VS, click File-New-project-web
This name is called: Musicbank, is a music shop bar.
Here we come to an empty just fine. We're going to build our own model/ef ....
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 except the reference + simple setting. Environment Match
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 for:
"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 "
},
Added here is a dependency on MVC, EF, and configuration.
The role of MVC is mainly used for the analysis of the controller, including the WEBAPI.
The EF is, of course, the database.
Configuration is used to read the local configuration for ease of setup. commands
Open the file "Project.json" we modify the commands section for:
"Commands": {
"Web": "Microsoft.AspNet.Hosting--config Hosting.ini",
"EF": "Entityframework.commands"
},
The main function of the Commands module is command-line execution, which simplifies the operation, such as " EF" when actually executing and represents "Entityframework.commands". Model
OK, here we first set up the folder Models, and then we right-click on the Model folder-add-class: Artist
Using System;
Using System.Collections.Generic;
Using System.ComponentModel.DataAnnotations;
Using System.ComponentModel.DataAnnotations.Schema;
Namespace Musicbank.models
{public
class Artist
{
[Key]
[Databasegeneratedattribute ( databasegeneratedoption.identity)] public
Guid Id {get; set;}
[Required]
public string Name {get; set;}
[Required]
public int Age {get; set;}
Public virtual list<audio> Audio {get; set;}}}
A singer, with a name and age, then there are n songs. Audio
Using System;
Using System.ComponentModel.DataAnnotations;
Using System.ComponentModel.DataAnnotations.Schema;
Namespace Musicbank.models
{public
class Audio
{
[Key]
[Databasegeneratedattribute ( databasegeneratedoption.identity)] public
Guid Id {get; set;}
[Required]
public string Name {get; set;}
[Required]
public int Type {get; set;}
[Required]
public string SRC {get; set;}
[Required]
Public Guid ArtistID {get; set;}
Public Artist Artist {get; set;}}}
The song also simplifies, a name, a type, a source file, belonging to a singer. Musiccontext
This must be no stranger to it, for the database query and so on all rely on this, is the essence of the EF.
Using Microsoft.Data.Entity;
Namespace Musicbank.models
{public
class Musiccontext:dbcontext
{public
dbset<audio> Audio { Get Set
dbset<artist> Artists {get; set;}}
Here you only need to add two tables on OK. Sampledata
For convenience, here I do the initialization of the data directly while creating the database, adding some default data.
Using Microsoft.Framework.DependencyInjection;
Using System;
Using System.Linq; Namespace Musicbank.models {public class Sampledata {public static void Initialize (IServiceProvider serv
Iceprovider) {var context = serviceprovider.getservice<musiccontext> (); if (context. Database.ensurecreated ()) {if (!context). Artists.any ()) {var Austen = context. Artists.add (new Artist {Name = "Austen", age = 21}).
Entity; var Dickens = context. Artists.add (new Artist {Name = "Dickens", age = 25}).
Entity; var cervantes = context. Artists.add (new Artist {Name = "cervantes", age = 27}).
Entity; Context.
Audio.addrange (New Audio () {Name = "Pride", Type = 1, Artist = Austen, SRC = "Pride.mp3"
New Audio () {Name = ' northanger ', Type = 2, Artist = Austen, SRC = "Northanger
. mp3 "}, new Audio () {
Name = "David", Type = 3, Artist = Dickens,
SRC = "David.mp3"}, new Audio () { Name = "Donquixote", Type = 1, Artist = Cervan
TES, SRC = "Donquixote.mp3"}); Context. SaveChanges (); }
}
}
}
}
First, this is a static method that needs to be passed in a "IServiceProvider"that can be invoked when the project is started.
After the method is entered we get to the "Musiccontext"above, and then we do database creation and data add work.
if (context. Database.ensurecreated ())
This sentence is primarily used to determine whether a database creation is required, if it is to be created, returns True, and then we determine whether there is data, and if the database table is empty, then we add some default data. configuration file Config.json
To add a file to the project root: "Config.json" in which you configure the database link fields as follows:
{"
Data": {"musicconnection": {"
ConnectionString": "
server= (localdb) \\mssqllocaldb;database= Musicbank-database; Trusted_connection=true; Multipleactiveresultsets=true "}}}
Start Configuration Startup.cs
The relevant methods in Startup.cs will be invoked to initialize the data when the project is started.
Here we need to do three things: get to Configuration Config.json, complete set up database file connection in constructor, complete initialization database related data in Configureservices method, complete in Configure method
Using Microsoft.AspNet.Builder;
Using Microsoft.AspNet.Hosting;
Using Microsoft.Data.Entity;
Using Microsoft.Dnx.Runtime;
Using Microsoft.Framework.Configuration;
Using Microsoft.Framework.DependencyInjection;
Using Musicbank.models; Namespace Musicbank {public class Startup {public startup (Ihostingenvironment env, Iapplicationenvironme NT appenv) {var builder = new Configurationbuilder (Appenv.applicationbasepath). Addjsonfile ("Config.json"). Addjsonfile ($ "config.{ Env.
Environmentname}.json ", optional:true); Builder.
Addenvironmentvariables (); Configuration = Builder.
Build ();
Iconfigurationroot 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 operation is basically complete, now see how to access the database data. Controllers
First add a folder to the root directory controllers, right-add-new item
Here I use a simple webapi to do the data demo, later in the article in detail write the data rendering related.
In the file AudioController.cs, we change the code to:
Using MICROSOFT.ASPNET.MVC;
Using Musicbank.models;
Using System.Collections.Generic;
Using System.Linq;
Namespace Musicbank.controllers
{
[Route ("Api/[controller]")] public
class Audiocontroller:controller
{
[fromservices] public
musiccontext db {get; set;}
[HttpGet]
Public ienumerable<audio> Get ()
{return
db. Audio.tolist ();
}
[HttpGet (' {name} ')]
Public Audio Get (string name)
{
Audio Audio = db. Audio.where (a => (a.name = = Name)). FirstOrDefault ();
return audio;
}
}
One property, two methods.
Here we can see that the Musiccontext attribute is not initialized, but the following can be invoked directly; This is because we have added a property "[Fromservices]", which means that the server can automatically assign values to the DB using annotations.
The following two methods return all the music lists, and return music-related information based on the music name.
Of course there are "[HttpGet]" attributes on two methods that specify the request type to get, and of course there are several others, such as "HttpPost" "Httpput" "Httpdelete". Run
There are two ways to run here, namely, the way IIS and the Web command line are.
IIS
Run this way directly, VS will open the browser and set the port. Web
Remember the place where the command line was written? One such line is:
"Web": "Microsoft.AspNet.Hosting--config Hosting.ini",
Here we start the parameters in the "Hosting.ini" file, we open the Hosting.ini file.
Server=microsoft.aspnet.server.weblistener
server.urls=http://localhost:5000
We can find the URL we visited, after running the URL copy to the browser to run the OK.
You will see this window in the run, and you can see that the dnx is actually running the program. And DNX can be cross-platform, which means you can run directly on the Mac.
effect
You can see that the interface call result for two methods is OK. Code
The project is complete and the code is packaged; The specific address is here:
Musicbank
The relevant code in the blog is focused on:
Https://github.com/qiujuer/BeFoot
========================================================
Author: 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 indicate the source: http://blog.csdn.net/qiujuer/article/details/48268729
Learn the open source, for open source, the beginner's mentality, and June mutual encouragement.
========================================================