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

    微软最近几年在跨平台上不断发力,很多.net程序员也摩拳擦掌,对微软寄以厚望。就在最近,微软还推出了asp .net core2.0预览版。

   通过对.net core的简单尝试,我发现以往我们开发MVC项目时,是通过新建一个.edmx文件来生成和更新实体模型,但是在core中,微软去掉了.edmx,所以下面我就来说一下core中如何生成model类。

 

环境:vs2017 + sqlserver2012

第一步   我们先创建测试库                                      

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 Install-Package Microsoft.EntityFrameworkCore.Tools

Run 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.cs

 

    完成!因为我们只介绍如何生成实体类,所以就到此为止,如果想操作实体类增删改查,我们还需要注册上下文在Startup.cs文件里,具体可以参考微软的说明文档:

    https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

 

别着急走啊!客官!如果本篇文章对你有帮助,请不要吝惜你的赞哦,请推荐一下!!

  

 

posted @ 2017-05-25 16:41  小丑不戴面具  阅读(10561)  评论(2编辑  收藏  举报