话说今年微软是很给力的,Win10算是吸引了大众的眼球了,而最新的.NET5框架更是OK。 git
最新的.NET5进行了开源,同时利用NuGet以及Node和Bower进行了跨平台化;这意味这能够直接在Mac或者Linux上使用.NET进行开发。 github
而最新的Mvc5和EF框架也算是进行了换脸了,跟以前Mvc4的项目都不同,若是进行移植除了核心代码能够拷贝过来,其余的通通要从新来过。 web
最近准备改版一下网站,因此尝试了一把最新的框架;固然因为如今仍是预览版因此改动什么的都超大,因此也走了很多弯路;特在此记录一下。 sql
因为是Beta7,而微软官方的说明文档和例子大部分能够适用,可是有些地方也是不对的,好比EF的命令,EF Beta3 与 Beta7差异很大,这也就是预览版的缺点,时不时的就改动了。
另外我这里使用的是VS2015而非Visual Studio Code ,毕竟有好点的确定就用好的啊。 api
打开VS,点击文件-新建-项目-Web
浏览器
这里起名叫作:MusicBank,就是一个音乐店吧。 服务器
在这里咱们来一个空的就好。咱们来本身创建Model/EF….
OK,项目创建好了后,咱们看见的是这样的。
app
能够看见咱们的项目实际上是在 Src 文件夹下面。而项目中除了引用+简单设置之外就没有任何东西。
项目有了,可是却并不能直接用,咱们须要搭建环境,好比咱们须要引入EF等等。
打开文件“project.json” 咱们修改dependencies部分为:
"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" },
在这里添加了对Mvc、EF、Configuration的依赖。
Mvc的做用主要用于控制器的解析等操做,包括了WebAPI。
EF固然就是数据库了。
Configuration 用来读取本地配置,方便设置。
打开文件“project.json” 咱们修改commands部分为:
"commands": { "web": "Microsoft.AspNet.Hosting --config hosting.ini", "ef": "EntityFramework.Commands" },
commands模块的主要做用是命令行执行,可简化操做,好比实际执行时输入 “ef” 便可表明 “EntityFramework.Commands”。
OK,在这里咱们先创建文件夹 Models,随后咱们在Model文件夹上右键-添加-类:
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; } } }
一个歌唱家,有个名字和年龄,而后有N个歌曲。
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; } } }
歌曲也简化了,一个名字,一个类型,一个源文件,属于某个歌唱家。
这个想必你们不陌生吧,用于数据库的查询等操做就全靠这个了;算是EF的精髓。
using Microsoft.Data.Entity; namespace MusicBank.Models { public class MusicContext : DbContext { public DbSet<Audio> Audio { get; set; } public DbSet<Artist> Artists { get; set; } } }
这里只须要添加两个表就OK。
为了方便,这里我直接在建立数据库的时候就进行数据的初始化工做,添加一些默认数据。
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(); } } } } }
首先这是一个静态方法,须要传入一个“IServiceProvider”,这个能够在项目启动的时候调用。
在方法进入后咱们获取到上面的“MusicContext”,而后咱们进行数据库建立与数据添加工做。
if (context.Database.EnsureCreated())
这句主要用于判断是否须要进行数据库建立,若是是将进行建立,同时返回true,然后咱们判断是否具备数据,若是数据库表为空,那么咱们添加一些默认数据。
在项目根目录添加文件:“config.json”在其中配置数据库连接字段以下:
{ "Data": { "MusicConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MusicBank-Database;Trusted_Connection=True;MultipleActiveResultSets=true" } } }
在项目启动的时候将会调用 Startup.cs 中的相关方法进行数据的初始化操做。
在这里咱们须要作三件事儿:
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); } } }
到这里咱们的初始化操做基本完成了,如今来看看如何访问数据库数据了。
首先在根目录添加文件夹 Controllers,右键-添加-新建项
在这里我就使用一个简单的WebAPI来进行数据演示了,后面会在文章中详细写写数据的渲染相关。
在文件 AudioController.cs 中,咱们更改代码为:
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; } } }
一个属性,两个方法。
在这里咱们能够看见 MusicContext 属性并无初始化,可是下面却能直接调用;这是由于咱们添加了一个属性“[FromServices]”,该属性意味着服务器能自动采用注解的方式对 db 进行赋值。
下面两个方法分别返回所有的音乐列表,和根据音乐名称返回音乐相关信息。
固然在两个方法上都有“[HttpGet]”属性,该属性指定了请求类型为 Get 方式,固然也有其余几种,如:“HttpPost”“HttpPut”“HttpDelete”等。
在这里运行方式有两种,分别是 IIS 与 Web 命令行的方式。
这种方式直接运行,VS将打开浏览器并设置端口。
还记得上面写到命令行的地方么?其中有这样一行:
"web": "Microsoft.AspNet.Hosting --config hosting.ini",
在这里咱们启动时候的参数在“hosting.ini”文件中,咱们打开 hosting.ini 文件。
server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:5000
能够找到咱们访问的Url,运行后把Url拷贝到浏览器运行就OK。
运行状况下你会看见这样的窗口,能够看出实际上是调用的dnx进行运行的程序。而 DNX 是能够跨平台的,这也就意味着能够直接在Mac上跑起来。
能够看出两个方法的接口调用结果是OK的。
项目完成了,代码也进行了打包;具体地址在这儿:
MusicBank
博客中的相关代码都集中在:
https://github.com/qiujuer/BeFoot
========================================================
做者:qiujuer
博客:blog.csdn.net/qiujuer
网站:www.qiujuer.net
开源库:github.com/qiujuer/Genius-Android
开源库:github.com/qiujuer/Blink
转载请注明出处:http://blog.csdn.net/qiujuer/article/details/48268729
—— 学之开源,用于开源;初学者的心态,与君共勉!
========================================================