.net core 根据数据库生成实体类

    微软最近几年在跨平台上不断发力,不少.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                                                      

由于.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

相关文章
相关标签/搜索