Tuesday, October 11, 2016

Fully Working Code Sample: ASP.NET MVC Core 1.1, Entity Framework Core, Database First (1)

1) First things first, you need installed the following things:

Visual Studio 2015 Update 3
.NET Core for Visual Studio


2) Open VS2015, create a new project called CASAPOC, this is an
ASP.NET Core Web Application (.NET Core)

3) Install Entity Framework 


To use EF Core, install the package for the database provider(s) you want to target. We are using MS SQL server

in VS2015, Tools ‣ NuGet Package Manager ‣ Package Manager Console

run Install-Package Microsoft.EntityFrameworkCore.SqlServer
run Install-Package Microsoft.EntityFrameworkCore.Tools –Pre  
run Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design 

find the project.json, and open it, under the "tools" section, you will find the snippet like this:

    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",


4) Supposed that we have a database table called TongTestPerson
creation script:

USE [KCMS2_Migration]
GO

/****** Object:  Table [dbo].[TongTestPerson]    Script Date: 10/11/2016 1:01:19 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TongTestPerson](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
 CONSTRAINT [PK_TongTestPerson] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



5) Find out the database connection string, something like


Data Source=CTSCKVCMSSQLTst;Initial Catalog=KCMS2_Migration;Integrated Security=True;Persist Security Info=True;MultipleActiveResultSets=True

6) in VS2015, Tools ‣ NuGet Package Manager ‣ Package Manager Console

run 

Scaffold-DbContext "Data Source=CTSCKVCMSSQLTst;Initial Catalog=KCMS2_Migration;Integrated Security=True;Persist Security Info=True;MultipleActiveResultSets=True" Microsoft.EntityFrameworkCore.SqlServer -outputDir  Entities -context KCMSContext -force -DataAnnotations


this will create the Entity classes and DbContext classes from the existing database KCMS2_Migration

No comments:

Blog Archive