In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what is ASP.NET Mvc5+EF7". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is ASP.NET Mvc5+EF7?"
Project preparation
Tool: VS2015/Visual Studio Code 2015 download address
Mvc5 VS plugin: the latest preview version is the download address of Beta7
Because it is Beta7, and most of Microsoft's official documentation and examples can be applied, but some places are also wrong, such as the command of EF, EF Beta3 is very different from Beta7, which 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, if you have something better, you must use it well.
Start
New project
Open VS and click File-New-Project-Web
It's called MusicBank, which is a music store.
Let's just have an empty one here. Let's build our own Model/EF... .
OK, after the project is established, what we see is like this.
You can see that our project is actually under the Src folder. On the other hand, there is nothing in the project except reference + simple settings.
Environmental collocation
There is a project, but it can not be used directly, we need to build the environment, for example, we need to introduce EF and so on.
Dependencies
Open the file "project.json" and 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"}
Dependencies on Mvc, EF, and Configuration are added here.
The role of Mvc is mainly used for operations such as controller parsing, including WebAPI.
EF is the database, of course.
Configuration is used to read the local configuration for easy setting.
Commands
Open the file "project.json" and modify the commands section to:
"commands": {"web": "Microsoft.AspNet.Hosting-- config hosting.ini", "ef": "EntityFramework.Commands"}
The main function of the commands module is to execute on the command line, which can simplify the operation, such as typing "ef" to represent "EntityFramework.Commands" during actual execution.
Model
OK, here we first create 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 {get; set;}}
A singer, with a name and age, and then 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 also simplified, a name, a type, a source file, belonging to a singer.
MusicContext
This must be no stranger to you, database queries and other operations rely on this; it can be regarded as 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 to OK.
SampleData
For convenience, I initialize the data directly when I create the 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 of all, this is a static method, and you need to pass in a "IServiceProvider", which can be called when the project starts.
After the method is entered, we get the "MusicContext" above, and then we create the database and add the data.
If (context.Database.EnsureCreated ())
This sentence is mainly used to determine whether the database needs to be created, if it is to be created, and return true, and then we determine whether there is data, if the database table is empty, then we add some default data.
Profile config.json
Add a file to the project root: "config.json" to configure the database link fields as follows:
{"Data": {"MusicConnection": {"ConnectionString": "Server= (localdb)\\ mssqllocaldb;Database=MusicBank-Database;Trusted_Connection=True;MultipleActiveResultSets=true"}}
Launch configuration Startup.cs
When the project starts, the relevant methods in Startup.cs will be called to initialize the data.
There are three things we need to do here:
Get the configuration config.json, which is done in the constructor
Set up the database file connection, which is done in the ConfigureServices method
Initialize the database-related data, which is done 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);}
Now that our initialization is almost complete, let's take a look at how to access the database data.
Controllers
First add the folder Controllers in the root directory, and right-add-create a new item
I will use a simple WebAPI to demonstrate the data here, and I will write about the rendering of the data in detail later in the article.
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 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 property is not initialized, but it can be called directly below; this is because we have added a property "[FromServices]", which means that the server can automatically annotate the db.
The following two methods return the full music list and music-related information based on the music name, respectively.
Of course, there is a "[HttpGet]" attribute on both methods, which specifies that the request type is Get, and of course there are several others, such as "HttpPost", "HttpPut", "HttpDelete" and so on.
Running
There are two ways to run it here, IIS and Web command line.
IIS
Run directly in this way, and VS will open the browser and set the port.
Web
Remember where the command line was written on it? There is a line like this:
"web": "Microsoft.AspNet.Hosting-config hosting.ini"
Here our startup parameters are in the "hosting.ini" file, and we open the hosting.ini file.
Server=Microsoft.AspNet.Server.WebListenerserver.urls= http://localhost:5000
We can find the Url we visit, and after running it, copy the Url to the browser and run OK.
When running, you will see a window like this, and you can see that the program is actually called dnx to run. DNX is cross-platform, which means you can run directly on Mac.
Write the picture description here.
Effect.
You can see that the result of the interface call of the two methods is OK.
At this point, I believe you have a deeper understanding of "what is ASP.NET Mvc5+EF7", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.