A Preliminary Study on the wonderful journey of ASP. NET Mvc5 + EF7
Collation
Microsoft is awesome this year. Win10 has attracted the attention of the masses, and the latest. NET5 framework is even more OK.
The latest. NET5 is open-source, and NuGet, Node, and Bower are used for cross-platform development. This means that it can be developed directly on Mac or Linux using. NET.
The latest Mvc5 and EF frameworks are also face-changing. They are different from the previous Mvc4 projects. If you do the porting, you can copy the core code, and all the others will be done again.
Recently, I was preparing to revise my website, so I tried the latest framework. Of course, because I am still in the preview version, I have made a lot of detours. I would like to record it here.
Project Preparation
Tool: VS2015/Visual Studio Code 2015
Mvc5 VS plug-in: the latest preview version is Beta7
Because it is Beta7, most of Microsoft's official instructions and examples can be used, but some of them are also incorrect. For example, EF command, EF Beta3 and Beta7 are very different, this is the disadvantage of the preview version, which is changed from time to time.
In addition, I use VS2015 instead of Visual Studio Code here. After all, I must use it well.
Start a new project
Open VS, click File-New-project-Web
The name here is MusicBank, which is a music store.
Here we can just leave it empty. Let's create a Model/EF ....
OK. After the project is set up, we can see this.
We can see that our project is actually under the Src folder. In addition to reference and simple settings, there is nothing in the project.
Environment matching
The project is ready, but it cannot be used directly. We need to build an environment, for example, we need to introduce EF and so on.
Dependencies
Open a file"Project. json"We modifyDependenciesPart:
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 the dependency on Mvc, EF, and Configuration.
The role of Mvc is mainly used for controller parsing and other operations, including WebAPI.
EF is the database of course.
Configuration is used to read local configurations for ease of Configuration.
Commands
Open a file"Project. json"We modifyCommandsPart:
commands: { web: Microsoft.AspNet.Hosting --config hosting.ini, ef: EntityFramework.Commands },
The main function of the commands module is to execute commands, which can simplify operations, such"Ef"Can represent"EntityFramework. Commands".
Model
OK. Here we will first create a folderModelsThen, right-click the Model folder and choose "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 { get; set; } } }
A singer has a name and age, and then has 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 is simplified. A name, a type, and a source file belong to a certain singer.
MusicContext
This is certainly not a stranger to everyone. It depends on database queries and other operations; it is the essence of EF.
using Microsoft.Data.Entity;namespace MusicBank.Models{ public class MusicContext : DbContext { public DbSet
Audio { get; set; } public DbSet Artists { get; set; } } }
Here, you only need to add two tables.
SampleData
For convenience, I will initialize the data directly when creating a database and add some default data.
using Microsoft.Framework.DependencyInjection;using System;using System.Linq;namespace MusicBank.Models{ public class SampleData { public static void Initialize(IServiceProvider serviceProvider) { var context = serviceProvider.GetService
(); 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 = cervantes, Src = DonQuixote.mp3 } ); context.SaveChanges(); } } } }}
First, this is a static method."IServiceProvider"This can be called when the project is started.
After entering the method, we get the above"MusicContext"And then create a database and add data.
if (context.Database.EnsureCreated())
This statement is mainly used to determine whether to create a database. If it is to be created and returns true, we can determine whether the database has data. If the database table is empty, then we add some default data.
Configuration file config. json
Add a file in the project root directory: "config. json", and configure the database link field as follows:
{ Data: { MusicConnection: { ConnectionString: Server=(localdb)\mssqllocaldb;Database=MusicBank-Database;Trusted_Connection=True;MultipleActiveResultSets=true } }}
Start Startup. cs
When the project is started, related methods in Startup. cs will be called for data initialization.
Here we need to do three things:
Get config. json configuration, complete database file connection setup in the constructor, complete database data initialization in the ConfigureServices method, and complete the configuration in the 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, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile(config.json) .AddJsonFile($config.{env.EnvironmentName}.json, optional: true); builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext
(options => { options.UseSqlServer(Configuration[Data:MusicConnection:ConnectionString]); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseStaticFiles(); app.UseMvc(); SampleData.Initialize(app.ApplicationServices); } }}
At this point, the initialization operation is basically completed. Now let's take a look at how to access the database data.
Controllers
First, add a folder in the root directory.Controllers, Right click-add-new item
Here I will use a simple WebAPI for data demonstration. Later I will write Data Rendering details in the article.
In the AudioController. cs file, we changed the code:
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
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 attribute and two methods.
Here we can see that the MusicContext attribute is not initialized, but can be called directly below; this is because we have added an attribute"[FromServices]"This attribute means that the server can automatically assign values to the db using annotations.
The following two methods return the list of all music and the information about music based on the music name.
Of course, both methods have the "[HttpGet]" attribute, which specifies the request type as the Get method, and of course there are several other types, such: "HttpPost", "HttpPut", and "HttpDelete.
Run
There are two running methods: IIS and Web command line.
IIS
In this way, VS will open the browser and set the port.
Web
Do you still remember the place where the command line was written above? There is a line like this:
web: Microsoft.AspNet.Hosting --config hosting.ini,
Here, we open the hosting. ini file in the parameter "hosting. ini" file during startup.
server=Microsoft.AspNet.Server.WebListenerserver.urls=http://localhost:5000
You can find the Url we accessed and copy the Url to the browser to run it.
You will see this window during running, and we can see that it is actually called.DnxProgram. DNX can be used across platforms, which means it can be run directly on Mac.
Effect
The interface call result of the two methods is OK. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxoMSBpZD0 = "code">