首页 > 代码库 > [.Net Core] EF Core实践(DB First)

[.Net Core] EF Core实践(DB First)

一、开发环境:

VS2015,

.Net Core 1.0.0-preview2-003156

 

二、准备数据: 

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

 

 

三、解决方案:

新建项目:

File --> New --> Project -->  ASP.Net Core Web Application(.Net Core) -- > Empty --> OK

技术分享

技术分享

 

 

添加EF Core引用:

编辑project.json文件,在【dependencies】和【tools】两个节点内添加下面代码

技术分享

【dependencies】节点:

"Microsoft.EntityFrameworkCore.SqlServer": "1.0.4",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.4",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

【tools】节点:

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

添加后结果如图:

技术分享

 

 

 

链接数据库生成DbContext及Model对象:

在Package Manager Console内执行:

Scaffold-DbContext "Data Source=.;Initial Catalog=Blogging;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

技术分享

执行成功后为在项目中生成Models文件夹及DbContext和Model对象:
技术分享

 

[.Net Core] EF Core实践(DB First)