How to Apply Entity Framework and coreentity in ASP. NET Core

Source: Internet
Author: User
Tags db connect

How to Apply Entity Framework and coreentity in ASP. NET Core

First, I would like to remind you that. NET Core and the Library of the classic. NET Framework are not generic, including Entity Framework!

What should I do? Don't worry, Microsoft is. NET Core is released.. NET Core version Entity Framework, specific configuration methods and classic. NET Framework version is slightly different, the following content is to lead everyone in ASP.. NET Core.

Note: Currently, some tools are in the Preview version. The official version may be slightly different.

Preparations:

1. We recommend using VS2015 Update3 as your IDE,: http://www.bkjia.com/softjc/446184.html

2. You need to install the. NET Core runtime environment and development tools, provided here VS version: http://www.bkjia.com/softs/472362.html

3. You need an 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 nvarchar(50),   Age int )  INSERT INTO Student VALUES('Bear',18) INSERT INTO Student VALUES('Frank',20)

Create a project

Create a project in VS. select ASP. NET Core Web Application (. NET Core) and enter the project name TestEFInNetCore.

Next, select Web Application and No Authentication for identity Authentication on the right.

Install Entity Framework

Open Tool> NuGet Package Manager> Package Manager Console.

Run the following command on the Pack Manager Console:

Install-Package Microsoft. EntityFrameworkCore. SqlServer

Install-Package Microsoft. EntityFrameworkCore. Tools-Pre

Install-Package Microsoft. EntityFrameworkCore. SqlServer. Design

Open Project. json and add the following configuration in the node tool:

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

This is why VS automatically downloads the corresponding package to your local device. Currently, this is the preview version.

Note: https://docs.efproject.net/en/latest/intro.html

Generate database Mapping

Run the following command on the Pack Manager Console:

Scaffold-DbContext "{Your DB connect string}" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

{Your DB connect string}: Your database connection string

Microsoft. EntityFrameworkCore. SqlServer: The target database is SQL Server.

-OutputDir Models: directory for storing generated files. The current directory is the Models directory under the root directory.

Then the engine will try to connect to your SQL Server database and generate files in your specified directory.

Find a *** Context. cs in the directory and open it. You will find the following method,

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, just like the warning written in the code automatically generated. In the next step, let's read the configuration from etettings. json.

In *** Context. cs, add an attribute to store ConnectionString. In addition, we need to rewrite the OnConfiguring method. The complete code should be like this:

public static string ConnectionString { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {   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};password={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};password={your password};"   },   "Logging": {     "IncludeScopes": false,     "LogLevel": {       "Default": "Debug",       "System": "Information",       "Microsoft": "Information"     }   } }

Open Startup. cs and add the following code in the ConfigureServices (IServiceCollection services) method:

TestNetCoreEFContext. ConnectionString = Configuration. GetConnectionString ("TestNetCoreEF ");

The complete code should be as follows:

public void ConfigureServices(IServiceCollection services) {   //config the db connection string   TestNetCoreEFContext.ConnectionString = Configuration.GetConnectionString("TestNetCoreEF");    // Add framework services.   services.AddMvc(); }

About calling Entity Framework

Really, believe me, just like the old one, just like the old one.

Models.TestNetCoreEFContext context = new Models.TestNetCoreEFContext();var StudentList = context.Student.ToList();

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.