Mvc5+ef6 Complete Tutorial 17--upgrade to EFCore2.0

Source: Internet
Author: User
Tags httpcontext

EF Core 2.0 was released last week and we are also upgrading to core

The article is based on vs2017, please install the vs2017 (15.3) First of all.

This article mainly tells the difference point, and the same as before will not repeat.

Article Directory (difference point):

I. New project, changes in EF configuration/use process

Second, the change of authentication mode (achieve similar to the original form authentication effect)

Third, the use of native SQL mode changes

Four, read the config process (by default, the Web. config is canceled and the JSON configuration file is read instead)

One, EF use

There are some changes in the configuration process when you use EF core to create a new project.

Let's start with a new project.

Select the following template

First, install and configure EF.

1. menu bar Select Tools à NuGet package Manager à Package Manager Console

Input: Install-package Microsoft.EntityFrameworkCore.SqlServer

2. Build a model as test data

Open folder models, add Class Sysuser

3. New Folder Dal, used to place EF related classes.

New context, similar to the previous article, such as, no longer elaborate.

4. Add Di (Dependency injection, Dependency injection) to the context

Before we talked about the principle and implementation of DI, ASP. NET core implements DI by default, and the service is registered at startup and obtained through constructors.

We just need to fill in the blanks as required by the framework.

Open Startup.cs, register the context, as in the box below

Modify the matching defaultconnection

Open the Appsettings.json file and add the configuration section:

Add test data to build the database structure

Startup, modify the Configure method and call the method you just called.

Run the Web site and you can see that both the database and the test data have been generated.

5. Using data in control

The control is added in the same way as before, but a setting option appears the first time you add control.

Right-click the Controls folder, choose menu AddàControl, the first time will appear add MVC Dependencies settings, we choose Minimal Dependencies

When added, a TXT document ScaffoldingReadMe.txt will appear, which can be deleted.

We add a control to read the data in the database.

The main difference is the way you get the context, injected through a constructor function.

Before we were all directly new a context, originally:

Privite xxxcontext db=new xxxcontext ();

Right now:

We add a breakpoint debug, you can see the list of the user has been obtained.

In addition, when you create a new controller, using a template with a view, you will find that the default is asynchronous, similar to the following:

Public Async task<iactionresult> Index()

{

return View (await _context. XXX . Tolistasync ());

}

Asynchronous is primarily for database operations, and if concurrency is small (such as Administrator's background management interface), it is not necessary. If there is more concurrency, ascension is obvious. The third part of our project will require selective use of async depending on the size of the preset concurrency traffic.

Second, identity verification

Originally configured as form authentication in Web. config, the Web. config is now out of the way, and of course it is not done by default.

Let's take a look at how the configuration for authentication is implemented in Aspnetcore.

Preparatory work:

Pack a bag first install-package Microsoft.AspNetCore.Authentication.Cookies

To create a new AccountController, add a login action and a matching view to complete the login. (as in the previous tutorial, no longer elaborate)

First, open the Startup.cs

1. Configuring Cookie Middleware in Configureservices

2. Using cookie Middleware in Configure: App.useauthentication ();

Note : Efcore 1.1 and 2.0 are not the same, if the 1.1 version needs to make the following changes (almost two of the contents of the method just swapped):

1. Add the following box to enable validation in the Configuraservices method.

2. Configuring validation related information in the Config method

Second, complete the login function

We're going to homecontroller. Configuring the Index method requires validation

When you visit the address again, you can see the jump to the login screen.

Next, we'll finish the login screen.

login.cshtml Add a form

Shown below

Below we add the login method in AccountController to complete the logon.

The core is to build an instance of ClaimsPrincipal .

I directly give a specific approach, the actual application of the direct modification of this method can be.

We're not going to. Database validation, directly define a testuser

Front desk to get login username, use @User.Identity.Name .

We add one item to the menu:

<li><a>current User: @User .identity.name</a></li>

Results:

Another way to log out is:

Await httpcontext.signoutasync ("Mycookieauthenticationscheme");

Simpler is no longer a demonstration.

Note :1.1 version Log out method is

HttpContext.Authentication.SignOutAsync ("mycookieauthenticationscheme ");

Official documentation about the login instructions:

Https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie

Third, native SQL

The use of native SQL is divided into two categories: Query and update.

The update is the same as before and can refer to my previous article http://www.cnblogs.com/miro/p/4518811.html

code example:

String sql= "DELETE from [Sysuserrole] WHERE [sysuserid][email protected]";

SqlParameter[] paras = new SqlParameter[]{

new SqlParameter("@userId", userId)

};

int res = _context. Database.executesqlcommand (SQL, paras);

The practice of database.sqlquery or dbset.sqlquery is not available before querying.

Returns an entity with Fromsql in Core2.0, for example:

int id=1;

String sql= "select * from Sysuser WHERE id={0}"

var user=_context. Sysusers.fromsql (SQL, id); Omitted from the back

This does not have much practicality, because queries can be easily implemented without SQL.

A general example is given below:

string query = @ " Complex of SQL statement ";

SqlParameter[] paras = new SqlParameter[]{

new SqlParameter("@roleId", Roleid)

}; Add some parameters

var conn = _context. Database.getdbconnection ();

Try

{

Conn. Open ();

using (var command = conn. CreateCommand ())

{

Command.commandtext = query;

Command. Parameters.addrange (paras);

dbdatareader reader = command. ExecuteReader ();

// the following processing of the resulting Reader, slightly

}

}

Catch (Exception)

{

throw;

}

Finally

{

Conn. Close ();

}

We generally use the while loop to process the resulting reader, a little.

Iv. reading the config process

Finally, the problem with the configuration file.

Aspnetcore the Web. config is canceled by default and read the JSON configuration file instead.

1, we first go to Appsettings.json to add a row of data.

2. Similar to using context, add a service in Startup.cs > configureservices

3. Use in Controller

Add a breakpoint debugging, you can see that you can already fetch the value.

Summarize

ASPNETCore2.0 made a relatively large change, some in the 1.1 usage to 2.0 directly abandoned, or more radical. There are also some other minor details that have been changed, such as when specific items are encountered.

We first learn how to use, have time to experience the advantages of Core2.0 practice.

In addition, questions about some Core2.0 can be viewed at the following address

Https://github.com/aspnet/Security/issues

For example, I have a problem with authentication from 1.1 to 2.0, and the solution is to find

https://github.com/aspnet/Security/issues/1310

Wish Learning Progress:)

Mvc5+ef6 Complete Tutorial 17--upgrade to EFCore2.0

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.