. Net core generates entity classes based on the database,. netcore
Microsoft has been making great efforts in cross-platform development in recent years. Many. net programmers are also very keen on Microsoft. Recently, Microsoft also released the asp. net core2.0 preview version.
Through. net core, I found that when we used to develop MVC projects, we created a new one. the edmx file generates and updates the object model, but Microsoft removes it from the core file. edmx, so let's talk about how to generate the model class in core.
Environment: vs2017 + sqlserver2012
First, create a test database.
CREATE DATABASE [Blogging];GOUSE [Blogging];GOCREATE TABLE [Blog] ( [BlogId] int NOT NULL IDENTITY, [Url] nvarchar(max) NOT NULL, CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId]));GOCREATE 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);GOINSERT INTO [Blog] (Url) VALUES('http://blogs.msdn.com/dotnet'),('http://blogs.msdn.com/webdev'),('http://blogs.msdn.com/visualstudio')GO
Step 2 create a. net core project
Omitted
Step 3 install ef
Because the. net core project does not reference ef, We need to manually introduce ef: Tools-> NuGet Package Manager-> Package Manager Console
Run Install-Package Microsoft. EntityFrameworkCore. SqlServer
RunInstall-Package Microsoft.EntityFrameworkCore.Tools
RunInstall-Package Microsoft.EntityFrameworkCore.SqlServer.Design
Install with nuget:
Step 4: Create an object model through the database
Tools-> NuGet Package Manager-> Package Manager ConsoleRun 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. if the above error is reported, you can turn off vs and re-open it and try again.
Scaffold-DbContext "Server =.; Database = Blogging; Trusted_Connection = True;" Microsoft. EntityFrameworkCore. SqlServer-OutputDir Models
The project generates a model folder containing the entity class and context BloggingContext. cs.
Done! Because we only introduce how to generate object classes, so far, if you want to operate object classes for addition, deletion, modification, and query, we also need to register the context in Startup. for details about the cs file, refer to Microsoft's instructions:
Https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db