How to apply the entity Framework in ASP. NET Core

Source: Internet
Author: User
Tags db connect connectionstrings

Note: The code example mentioned in this article > How to using the Entity Framework DB first in ASP.

How to apply the entity Framework in ASP. NET Core

The first thing to remind you is that the. NET core and the classic. NET Framework library are not generic, including entity framework!

What do you do? Don't worry, Microsoft has released the. NET core version of the entity Framework for. NET core, with a slight difference between the configuration method and the classic. NET Framework version, and the following is to lead you to apply entity in ASP. Framework DB first.

Note: Some tools are currently in the preview version, and the official version may be slightly different.

Pre-Preparation:

1. It is recommended to use VS2015 Update3 as your ide,:www.visualstudio.com

2. You need to install the. NET Core runtime environment and development tools, which are available in VS version: Www.microsoft.com/net/core

3. You need to have a SQL Server database.

The structure should be like this.

Create DATABASE Testnetcoreef go use testnetcoreef go CREATE TABLE Student (     ID int Identity primary key,     Name Nvar char (+), age     int)   INSERT into Student values (' Bear ', +) insert into Student values (' Frank ', 20)

Create a project

New project in VS, project type selected in ASP. NET Core WEB application, enter project name Testefinnetcore

Next select Web application, right Authentication selection: No authentication

Installing the Entity Framework

Open Tool,NuGet Package Manager, Packagemanager Console

Run the following command in the Pack Manager console:

Install-package Microsoft.EntityFrameworkCore.SqlServer

Install-package Microsoft.entityframeworkcore.tools–pre

Install-package Microsoft.EntityFrameworkCore.SqlServer.Design

Open Project.jsonand add the following configuration to the node tool:

"Tools": {     "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",     .....}

This is vs will automatically download the corresponding package to your local, currently this is the preview version, the official version please pay attention to: https://docs.efproject.net/en/latest/intro.html

Build Database Mapping

In the Pack Manager console, run the following command:

Scaffold-dbcontext "{Your DB connect string}" Microsoft.entityframeworkcore.sqlserver-outputdir Models

{Your DB connect string}: Your database connection string

Microsoft.EntityFrameworkCore.SqlServer: Target database is SQL Server

-outputdir Models: The directory where the files are generated, the current directory is the Models directory under the root directory

The engine then tries to connect to your SQL Server database and generate the files in the directory you specify.

Find a ***context.cs in the directory and open it, you will find a method like the following,

protected override void Onconfiguring (Dbcontextoptionsbuilder optionsbuilder) {    #warning to protect potentially Sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.    Optionsbuilder.usesqlserver (@ "{Your SQL connect string}");}

We should not put the connection string here, as is the case with the warning written in the auto-generated code. Next work, let's read the configuration from the Appsettings.json.

Add a property in ***context.cs to hold the ConnectionString, and we need to rewrite the Onconfiguring method, and the complete code should look like this:

public static string ConnectionString {get; set;} protected override void Onconfiguring (Dbcontextoptionsbuilder optionsb Uilder) {     optionsbuilder.usesqlserver (ConnectionString);}

Open Appsetting.json and add the following code:

"ConnectionStrings": {     "Testnetcoreef": "Data source={your SQL Server host address};initial Catalog=testnetcoreef; User Id={your username};p assword={your password}; "},

The complete code should look like this:

{"     ConnectionStrings": {         "Testnetcoreef": "Data source={your SQL Server host Address};initial catalog= Testnetcoreef;user id={your username};p assword={your password}; "     },     " Logging ": {         " includescopes ": false ,         "LogLevel": {             "Default": "Debug", "             System": "Information",             "Microsoft": "Information"         }     } }

Open Startup.cs and add the following code to the Configureservices (Iservicecollection Services) method:

The complete code should look like this:

public void Configureservices (iservicecollection services) {     //config the DB connection string     testnetcoreefcontext.connectionstring = configuration.getconnectionstring ("Testnetcoreef");       ADD Framework Services.     Services. Addmvc (); }

About calling the entity Framework

Really, believe me, like before a hair, really a hair.

Models.testnetcoreefcontext context = new Models.testnetcoreefcontext (); var studentlist = context. Student.tolist ();

Finally: Complete code sample and how to run it, visit: How to using the Entity Framework DB first in ASP.

How to apply the entity Framework in ASP. NET Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.