Asp. Net Core: permission management system (3) using EntityFramework Core P,

Source: Internet
Author: User
Tags postgresql introduction

Asp. Net Core: permission management system (3) using EntityFramework Core P,

0 Asp. Net Core: permission management system (0)

1 Asp. Net Core project practice-permission management system (1) Use AdminLTE to build a front-end

2 Asp. Net Core project practice-permission management system (2) function and entity Design

3. Asp. Net Core: permission management system (3) using PostgreSQL through EntityFramework Core

4 Asp. Net Core project practices-permission management system (4) multi-project hierarchical implementation of dependency injection, warehousing, and services

5 Asp. Net Core project practices-permission management system (5) User Logon

6 Asp. Net Core project practice-permission management system (6) function Management

7 Asp. Net Core project practice permission management system (7) Organization Management

Github Source Code address

0 PostgreSQL installation and configuration 0.0 PostgreSQL Introduction

Since Asp. Net Core has the biggest feature of cross-platform, it can be used together with a cross-platform database. PostgreSQL is a powerful open-source database system. After more than 15 years of active development and continuous improvement, PostgreSQL has gained a high reputation in the industry in terms of reliability, stability, and data consistency. Currently, PostgreSQL can run on all mainstream operating systems, including Linux, Unix (AIX, BSD, HP-UX, sgi irix, Mac OS X, Solaris, and Tru64), and Windows. PostgreSQL is a complete transaction security database that fully supports foreign keys, Federation, views, triggers, and stored procedures (and supports the development of stored procedures in multiple languages ). It supports most SQL: 2008 standard data types, including integer, numerical value, Boolean, byte, dense, date, interval, and time, it also supports storing Binary large images, including images, sounds, and videos. PostgreSQL provides native programming interfaces for many advanced development languages, such as C/C ++, Java, and ,.. Net, Perl, Python, Ruby, Tcl, ODBC, and other languages.

0.1 PostgreSQL installation and configuration

Go to the PostgreSQL official website to download the version that meets your own system and start installation. From my own installation experience, there is nothing to pay special attention to, just install it step by step as prompted, at the end, select the following language as needed and set the logon password for the Super User role S.

Create a role used by the System

Open the installed PostgreSQL database and enter the password to enter the management interface. Right-click "Logon role" and create a role named "fonour". On the "role Permissions" tab, select all the functions that can be selected.

Right-click the PostgreSQL server and choose disconnect server. Right-click the "properties" menu, enter the new "fonour" role as the user name in the pop-up window, enter the password, and check "Remember password. OK. Connect.

1. Use CodeFirst method of EntityFrameworkCore to create a database 1.0 create DbContext in the Fonour. EntityFrameworkCore Project

Because both EF Core and PostgreSQL need to be used now, the use of EF Core is much different from that of EF6.0, and many problems have been encountered during use, especially when PostgreSQL uses a Guid-type primary key, these pitfalls will be easily recorded later.

0. Add related dependencies.

The dependencies to be added are described as follows:

  • Npgsql. EntityFrameworkCore. PostgreSQL

The basic class library that supports EF Core provided by PostgreSQL data is the basis for using PostgreSQL databases through EF Core.

  • Npgsql. EntityFrameworkCore. PostgreSQL. Design

A primary key of the Guid type (uuid for the Postgre data type) must be used. It is okay if you do not add a primary key of the int or long type.

  • Microsoft. EntityFrameworkCore. Tools

The EF Core tool is required for CodeFirst database migration.

  • Fonour. Domain

A class library project created by ourselves contains the definition of entities such as organization, function, role, and user.

There are multiple ways to add reference dependencies. You can run the Install-Packege command on the NuGet Package Manager Console.

PM> Install-Package Npgsql.EntityFrameworkCore.PostgreSQLPM> Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.DesignPM> Install-Package Microsoft.EntityFrameworkCore.Tools

You can also search for the relevant class library in the NuGet Package Manager to install the library.

The most direct method is to directly modify the project. json configuration file. After the project. json configuration file is finally modified, the content is as follows.

{  "version": "1.0.0-*",  "dependencies": {    "Fonour.Domain": "1.0.0-0",    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",    "NETStandard.Library": "1.6.0",    "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.1",    "Npgsql.EntityFrameworkCore.PostgreSQL.Design": "1.0.1"  },  "frameworks": {    "netcoreapp1.0": {      "imports": [        "dotnet5.6",        "portable-net45+win8"      ]    }  },  "tools": {    "Microsoft.EntityFrameworkCore.Tools": {      "version": "1.0.0-preview2-final",      "imports": [        "portable-net45+win8+dnxcore50",        "portable-net45+win8"      ]    }  }}

Note: In the frameworks section, if the default value is the netstandard1.6 framework, you must modify it. Otherwise, the system will prompt that related dependencies are not supported.

1. Create DbContext

According to EF Core's requirements on multiple-to-multiple associations, two correlated entities, UserRole and RoleMenu, were added, and the original entities were adjusted.

public class UserRole{    public Guid UserId { get; set; }    public User User { get; set; }    public Guid RoleId { get; set; }    public Role Role { get; set; }}
public class RoleMenu{    public Guid RoleId { get; set; }    public Role Role { get; set; }    public Guid MenuId { get; set; }    public Menu Menu { get; set; }}

Create a data context operation class under the Fonour. EntityFrameworkCore project named "FonourDBContext", and add the definition of DbSet for the relevant entities of the permission management system. The final code is as follows:

Public class FonourDbContext: DbContext {public FonourDbContext (DbContextOptions <FonourDbContext> options): base (options) {} public DbSet <Department> Departments {get; set ;} public DbSet <Menu> Menus {get; set;} public DbSet <Role> Roles {get; set;} public DbSet <User> Users {get; set ;} public DbSet <UserRole> UserRoles {get; set;} public DbSet <RoleMenu> RoleMenus {get; set;} protected override void OnModelCreating (ModelBuilder builder) {// UserRole associated configuration builder. entity <UserRole> (). hasKey (ur => new {ur. userId, ur. roleId}); // RoleMenu associated configuration builder. entity <RoleMenu> (). hasKey (rm => new {rm. roleId, rm. menuId}); builder. entity <RoleMenu> (). hasOne (rm => rm. role ). withiterator (r => r. roleMenus ). hasForeignKey (rm => rm. roleId ). hasForeignKey (rm => rm. menuId); // enable the Guid primary key type Extension builder. hasPostgresExtension ("uuid-ossp"); base. onModelCreating (builder );}}
1.1 configure database connection in the Fonour. MVC Project

0. Add related dependencies.

In Asp. in. Net Core, the configuration file in json format is used to configure system-related parameters, and related configuration files are managed in a unified manner through ConfigurationBuilder to obtain the configuration instance of IConfigurationRoot, obtain the configuration file configuration node information. To use services related to the configuration file, you need to add dependencies.

  • Microsoft. Extensions. Configuration
  • Microsoft. Extensions. Configuration. FileExtensions
  • Microsoft. Extensions. Configuration. Json

You also need to add references to the Fonour. EntityFrameworkCore project.

The final configuration of the project. json file of the Fonour. MVC project is as follows:

{  "dependencies": {    "Microsoft.NETCore.App": "1.0.1",    "Microsoft.AspNetCore.Diagnostics": "1.0.0",    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",    "Microsoft.Extensions.Logging.Console": "1.0.0",    "Microsoft.AspNetCore.Mvc": "1.0.1",    "Microsoft.AspNetCore.StaticFiles": "1.0.0",    "Microsoft.Extensions.Configuration": "1.0.0",    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",    "Microsoft.Extensions.Configuration.Json": "1.0.0",    "Fonour.EntityFrameworkCore": "1.0.0-*"  },  "tools": {    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  },  "frameworks": {    "netcoreapp1.0": {      "imports": [        "dotnet5.6",        "portable-net45+win8"      ]    }  },  "buildOptions": {    "emitEntryPoint": true,    "preserveCompilationContext": true  },  "runtimeOptions": {    "configProperties": {      "System.GC.Server": true    }  },  "publishOptions": {    "include": [      "wwwroot",      "web.config"    ]  },  "scripts": {    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  },  "runtimes": {    "win10-x64": {}  }}

1. added the appsettings. json configuration file.

Right-click the Fonour. MVC project and add an Asp. Net configuration file type named etettings. json.

Currently, the appsettings. json file is mainly used to define database connection strings. The content is as follows:

{  "ConnectionStrings": {    "Default": "User ID=fonour;Password=123456;Host=localhost;Port=5432;Database=Fonour;Pooling=true;"  }}

2. enable database connection

Define an IConfigurationRoot attribute in Startup. cs, and manage the configuration file in the system Startup class Startup. cs constructor.

public IConfigurationRoot Configuration { get; }public Startup(IHostingEnvironment env){    var builder = new ConfigurationBuilder()        .SetBasePath(env.ContentRootPath)        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);    builder.AddEnvironmentVariables();    Configuration = builder.Build();}

Obtain the database connection string in the ConfigureServices method and add the Database Connection Service.

Public void ConfigureServices (IServiceCollection services) {// obtain the database connection string var sqlConnectionString = Configuration. getConnectionString ("Default"); // Add data context services. addDbContext <FonourDbContext> (options => options. useNpgsql (sqlConnectionString); services. addMvc ();}
1.2 use the CodeFirst database migration command to create a database

There are two methods for database migration in EntityFrameworkCore.

0 use the command line tool

In the application root directory, press shift and right-click, select "Open command window here", and enter the database migration command

dotnet ef migrations add Initdotnet ef database update

1. Use the Package Manager Console

In the Package Manager Console, select Fonour. EntityFrameworkCore as the default project, and enter the following command to automatically create a database migration file.

Add-Migration Init

Note that you must set Fonour. MVC as the startup project.

After the execution is complete, the database migration file is added to the project.

Enter the following command to update the database.

Update-Database

After the prompt is displayed, check the database and the database table.

2. Data Initialization

To ensure the normal operation of the system, we need to initialize the system data. The data to be initialized includes the following content:

  • In the user table, insert a super administrator user whose username is admin.
  • The function menu table adds four basic data items: organization management, role management, user management, and function management.
  • An organizational unit information is inserted into the organizational unit table (mainly because the user table has a foreign key for external mentid)

Add a new data initialization class in the Fonour. EntityFrameworkCore project named SeedData. cs. The modification is as follows:

Public static class SeedData {public static void Initialize (IServicePr {using (var context = new FonourDbCon {if (context. users. any () {return; // data already initialized} Guid required mentid = Guid. newGuid // Add a department context. parameters. add (new Department {Id = mongomentid, Name = "Fonour Group Headquarters", ParentId = Guid. empty}); // Add a super administrator user context. users. add (new User {UserName = "admin", Password = "123456", // Name = "Super administrator", mongomentid = mongome }); // added four basic function menus: context. menus. addRange (new Menu {Name = "organization management", Code = "Department", SerialNumber = 0, ParentId = Guid. empty, Icon = "fa-link"}, new Menu {Name = "Role management", Code = "Role", SerialNumber = 1, ParentId = Guid. empty, Icon = "fa-link"}, new Menu {Name = "User Management", Code = "User", SerialNumber = 2, ParentId = Guid. empty, Icon = "fa-link"}, new Menu {Name = "function Management", Code = "Department", SerialNumber = 3, ParentId = Guid. empty, Icon = "fa-link"}); context. saveChanges ();}}}

Add the data initialization operation to the Configure method in Startup. cs of the Fonour. MVC project.

Public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {loggerFactory. addConsole (); if (env. isDevelopment () {// Exception Handling app in the development environment. useDeveloperExceptionPage ();} else {// Exception Handling app in the production environment. useExceptionHandler ("/Shared/Error");} // use the static file app. useStaticFiles (); // use Mvc to set the default route to the system logon app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller = Logi N}/{action = Index}/{id ?} ") ;}); SeedData. Initialize (app. ApplicationServices); // Initialize data}

Run the program. Check the database and find that the initialization data has been generated successfully.

3. Some pitfalls
  • To use a Guid-type primary key, you must add a reference to "Npgsql. EntityFrameworkCore. PostgreSQL. Design": "1.0.1". Note that version 1.0.0 is not supported.
  • To use a Guid-type primary key, you must enable uuid extension builder. HasPostgresExtension ("uuid-ossp") in the OnModelCreating Rewriting Method of DbContext ");
  • Entity Design of many-to-many relationships

In the previous EntityFramework, for multi-to-Multi-link entities, you only need to create two entities, which respectively contain the navigation attributes of one set of the other. Therefore, you do not need to create an associated entity class. For example, the User object contains the navigation attribute of an ICollection <Role> Roles and the Role object contains the navigation attribute of an ICollection <User> Users, EF automatically creates a User_Role table based on the relationship between objects. to modify the name of the intermediate table, configure the table.

In EF Core, you must create an object of the association.

  • Currently, EF Core does not support LayzingLoad.
4. Summary

This section mainly studies how to use PostgreSQL through EntityFramework Core, create a database based on the designed entity through CodeFirst database migration, and finally create a database based on the system requirements, some related data is initialized.

Next, we need to implement the user login function.

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

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.