MVC5 + EF6 complete tutorial 17 -- upgrade to EFCore2.0, 17 -- efcore2.0
EF Core 2.0 was released last week and we upgraded it to core.
This article is based on vs2017. Please install vs2017 (15.3) first ).
This article focuses on the differences.
Document directory (differences ):
1. Changes in the configuration/usage process of the newly created Project and EF
Ii. Changes in identity authentication methods (similar to the original form authentication)
Iii. Changes in the use of native SQL
4. Read the config file. (web. config is canceled by default and the json configuration file is read)
I. EF usage
When you use EF Core to create a project, the configuration process changes.
Create a project first.
Select the following template
1. install and configure EF
1. on the menu bar, choose TOOLS> NuGet Package Manager> Package Manager Console.
Input: Install-Package Microsoft. EntityFrameworkCore. SqlServer
2. Create a Model as the test data
Open the folder Models and add the class SysUser
3. Create a folder DAL to place EF-related classes.
The process of creating a new Context is similar to that in the previous article.
4. Add DI (dependency injection, dependency injection) to context)
Previously, we talked about the Principle and Implementation of DI. ASP. NET Core implements DI by default. The service is registered at startup and obtained through constructors.
We only need to fill in the blanks as required by the framework.
Open Startup. cs and register context, as shown in the following box.
Modify the DefaultConnection
Open the appsettings. json file and add the configuration section:
Add test data to generate database structure
Modify the Configure method in Startup and call the method just now.
Run the website to see that the database and test data have been generated.
5. Use Data in Control
The method for adding a Control is the same as before, but a setting option is displayed when you add a Control for the first time.
Right-click the Controls folder and select Add à Control from the menu. The Add MVC Dependencies setting will appear for the first time. Select Minimal Dependencies.
Then, a TXT file scaffoldingreadme.txt is displayed, which can be deleted.
We add a Control to read data in the database.
The main difference is that context is obtained through constructor injection.
Previously, we all directly added a new context, which turns out to be:
Privite XxxContext db = new XxxContext ();
Now:
After a breakpoint is added for debugging, the user list is displayed.
In addition, when creating a Controller, if you use a template with a view, you will find that the asynchronous method is used by default, similar:
Public async Task <IActionResult> Index ()
{
Return View (await _ context. XXX. ToListAsync ());
}
Asynchronization is mainly for database operations. If the concurrency is small (such as the administrator's background management interface), it is unnecessary. If the concurrency is high, the improvement is obvious. In the third part of the project, asynchronous mode is selected based on the preset concurrency access volume.
Ii. Authentication
It was originally configured as form authentication in web. config. Now web. config is no longer available. Of course, this method is not used by default.
Let's take a look at how to configure Identity Authentication in ASPNETCore.
Preparations:
Install-package Microsoft. AspNetCore. Authentication. Cookies
Create an AccountController and add a Login Action and its related View to log on. (this is the same as the previous tutorial. I will not elaborate on it)
1. Open Startup. cs
1. Configure Cookie middleware in ConfigureServices
2. Use Cookie middleware in Configure: app. UseAuthentication ();
Note: EFCore 1.1 and 2.0 are different. if the version is 1.1, you need to make the following changes (the content in almost two methods is changed ):
1. Add the content in the following box and enable verification in the replicaservices method.
2. Configuration verification information in the Config method
2. Complete the logon Function
We need to verify the Index method configured in HomeController.
When you access this address again, you can see that the logon page is displayed.
Next we will complete the login interface
Add a form for Login. cshtml
Shown below
Next we will add the Login method in AccountController to complete the logon.
The core is to build a ClaimsPrincipal instance.
I will give you a specific method. You can directly modify this method in actual application.
We will not go to the database for verification, and define a TestUser directly.
To obtain the logon username, use @ User. Identity. Name.
Add one to the menu:
<Li> <a> Current User: @ User. Identity. Name </a> </li>
Result:
In addition, the logout method is as follows:
Await HttpContext. SignOutAsync ("MyCookieAuthenticationScheme ");
It is relatively simple and will not be demonstrated.
Note: The logout method of Version 1.1 is
HttpContext. Authentication. SignOutAsync ("MyCookieAuthenticationScheme ");
Official documentation on logon instructions:
Https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie
Iii. Native SQL
Native SQL is divided into query and update.
Update is the same as before and can refer to my previous article http://www.cnblogs.com/miro/p/4518811.html
Sample Code:
String SQL = "DELETE FROM [SysUserRole] WHERE [SysUserID] = @ userId ";
SqlParameter [] paras = new SqlParameter [] {
New SqlParameter ("@ userId", userId)
};
Int res = _ context. Database. ExecuteSqlCommand (SQL, paras );
Database. SqlQuery or DbSet. SqlQuery cannot be used before the query.
FromSql is used in Core2.0 to return objects, for example:
Int id = 1;
String SQL = "SELECT * FROM SysUser WHERE ID = {0 }"
Var user = _ context. SysUsers. FromSql (SQL, id); // omitting
This kind of feature is not very practical, because it is easy to implement queries without SQL.
Below is a general example:
String query = @ "complex SQL statements ";
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 reader processed below, omitted
}
}
Catch (Exception)
{
Throw;
}
Finally
{
Conn. Close ();
}
We generally use the while loop to process the reader, omitted.
4. Read the config Process
Finally, let's talk about the configuration file.
By default, ASPNETCore cancels web. config and reads the json configuration file.
1. First add a row of data in appSettings. json.
2. Similar to using context, add a service to Startup. cs> ConfigureServices.
3. Use in Controller
After a breakpoint is added for debugging, you can see that the value has been obtained.
Summary
ASPNETCore2.0 has made a big change, and some of them are discarded directly from 1.1 to 2.0, which is still radical. There are also some other minor details that will be discussed when specific projects are met.
Let's learn how to use it first, and then try Core2.0's advantages when you are free.
For more information about Core2.0, visit the following address:
Https://github.com/aspnet/Security/issues
For example, if I encounter problems with 1.1 to 2.0 certification, the solution is to find
Https://github.com/aspnet/Security/issues/1310
Wish learning progress :)