微軟最近幾年在跨平臺上不斷髮力,不少.net程序員也摩拳擦掌,對微軟寄以厚望。就在最近,微軟還推出了asp .net core2.0預覽版。程序員
經過對.net core的簡單嘗試,我發現以往咱們開發MVC項目時,是經過新建一個.edmx文件來生成和更新實體模型,可是在core中,微軟去掉了.edmx,因此下面我就來講一下core中如何生成model類。web
環境:vs2017 + sqlserver2012sql
CREATE DATABASE [Blogging]; GO USE [Blogging]; GO CREATE TABLE [Blog] ( [BlogId] int NOT NULL IDENTITY, [Url] nvarchar(max) NOT NULL, CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId]) ); GO CREATE TABLE [Post] ( [PostId] int NOT NULL IDENTITY, [BlogId] int NOT NULL, [Content] nvarchar(max), [Title] nvarchar(max), CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]), CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE ); GO INSERT INTO [Blog] (Url) VALUES ('http://blogs.msdn.com/dotnet'), ('http://blogs.msdn.com/webdev'), ('http://blogs.msdn.com/visualstudio') GO
略
由於.net core 項目自己沒有引用ef,因此咱們須要手動引入ef: Tools -> NuGet Package Manager -> Package Manager Console
Run Install-Package Microsoft.EntityFrameworkCore.SqlServer
Run Run Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
經過nuget安裝:數據庫
Tools –> NuGet Package Manager –> Package Manager Console Run the following command to create a model from the existing database. If you receive an error stating The term 'Scaffold-DbContext' is not recognized as the name of a cmdlet, then close and reopen Visual Studio. 若是報了上面這個錯,能夠關掉vs再從新打開後再次嘗試。
Scaffold-DbContext "Server=.;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
項目會生成一個model文件夾,裏面有咱們須要的實體類和上下文BloggingContext.cssqlserver
完成!由於咱們只介紹如何生成實體類,因此就到此爲止,若是想操做實體類增刪改查,咱們還須要註冊上下文在Startup.cs文件裏,具體能夠參考微軟的說明文檔:測試
https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-dbspa
彆着急走啊!客官!若是本篇文章對你有幫助,請不要吝惜你的贊哦,請推薦一下!!.net