A wonderful journey to ASP. NET Mvc5 + EF7, mvc5ef7

Source: Internet
Author: User

A wonderful journey to ASP. NET Mvc5 + EF7, mvc5ef7

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.
Commencement

Create a 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 the file "project. json" and modify the dependencies section:

 "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 the file "project. json" and modify the commands section:

 "commands": { "web": "Microsoft.AspNet.Hosting --config hosting.ini", "ef": "EntityFramework.Commands" },

The commands module is mainly used for command line execution to simplify operations. For example, if you enter "ef" during actual execution, it will represent "EntityFramework. Commands ".

Model

OK. Here we first create the folder Models, and then 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> 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]
[Databasegeneratedattrition (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 {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> Audio { get; set; }  public DbSet<Artist> 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<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 = cervantes,       Src = "DonQuixote.mp3"      }     );     context.SaveChanges();    }   }  } }}

First, this is a static method.IServiceProvider", Which can be called when the project is started.

After entering the method, we get the"MusicContext", Then we 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:

The config. json configuration is obtained and completed in the constructor.
Set database file connection, completed in ConfigureServices Method
Initialize database-related data, completed 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<MusicContext>(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 the folder Controllers in the root directory, right-click and choose 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<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 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 database 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 a program that calls dnx for running. DNX can be used across platforms, which means it can be run directly on Mac.
Write the image description here

Effect

The interface call result of the two methods is OK.

The journey of ASP. NET Mvc5 + EF7 is now over. I hope you can start another wonderful journey of ASP. NET Mvc5 + EF7.

Related Article

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.