AspNetCore, asp. netcore
This chapter begins with a brief introduction of an image collection website that I have used in my spare time to collect images from some websites, that's meaningless. Here I name it"Love chart"; For a brief introduction to this website, you can refer to the content in the previous article.The birth of love picturesHere, I plan to explain how to use it step by step through some blogs.AspnetcoreMvc development, hope everyone will like it;
(Reverse engineering generates entity model)
First, we need to create a user table in sqlserver.To_UserInfoHere, I try to take some attributes as fields. The following is the table structure SQL:
USE [LovePicture.Db]GO/****** Object: Table [dbo].[To_UserInfo] Script Date: 2017/4/25 17:30:53 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[To_UserInfo]( [Id] [int] IDENTITY(1,1) NOT NULL, [UserName] [nvarchar](50) NOT NULL, [UserPwd] [nvarchar](50) NOT NULL, [Email] [nvarchar](50) NULL, [NickName] [nvarchar](20) NULL, [Tel] [nvarchar](20) NULL, [Sex] [bit] NOT NULL, [Introduce] [nvarchar](200) NULL, [HeadPhoto] [nvarchar](200) NULL, [Birthday] [nvarchar](20) NULL, [Addr] [nvarchar](200) NULL, [Blog] [nvarchar](200) NULL, [Status] [int] NOT NULL, [CreateTime] [datetime] NOT NULL, [LoginTime] [datetime] NULL, [Ips] [nvarchar](50) NULL, [LevelNum] [int] NOT NULL, CONSTRAINT [PK_To_UserInfo] PRIMARY KEY CLUSTERED ( [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO
The field does not need to be too clear. It is mainly used to learn how to generate entities. First, create a class library LovePicture. model, because I plan to use EF Core (full name: entity framework core) Here, we need to install the corresponding nuget package for this Class Library:
Microsoft. EntityFrameworkCore. Design
Install-Package Microsoft. EntityFrameworkCore. SqlServer
Install-Package Microsoft. EntityFrameworkCore. Tools
Install-Package Microsoft. EntityFrameworkCore. SqlServer. Design
Note that there are four packages. The netcore official website only provides the following three packages without the first one. We have practical experience that if you do not add the first package, an error will be prompted when the database generates the entity model. Here, I will not make the error message. If you are interested, please try it. When you come here, you also need to enter the execution command through the vs console:
Scaffold-DbContext "Server = 127.0.0.1, 1431; User Id = sa; Password = 123123; Database = LovePicture. Db;" Microsoft. EntityFrameworkCore. SqlServer-OutputDir Models
To put it simply, the parameters are as follows:
. Scaffold-DbContext: Execute the command
. Server =...: database link string
.-OutputDir Models: outputs an object to a folder named Models.
Notes for personal comprehension:
Vs2017 may have a problem. When you need to use reverse engineering to generate an object model in the newly created class library for the first time, if youDo not set this class library as the starting projectThe error cannot be generated successfully. I used many methods to solve the problem and even thought something was wrong with Dongxi, as a result, I found the answer to the related question in the Git question center. I only needed to set the startup Item to solve the problem. It surprised me.
At this point, if you follow the steps listed above, there should be no major problems, and the entity can be successfully generated through the sqserver database. Of course, other special circumstances are not guaranteed;
Use the generated entity model in MVC
First, create an ASP netcore Mvc project through vs2017. web, we need to know that the netcore project basically introduces other components through the nuget package, but the powerful vs allows us to directly pass through: right-click "dependency" of the web project-"add reference-" solution-"and select the name of another project, to add dependencies on other projects (mainly for the new vs version );
With the dependency, we will first rebuild itReverse EngineeringThe generated DbContext Code meets the needs of Mvc in the Web. Open the LovePicture_DbContext.cs file in the model class library and you can see that we are familiar with structures similar to other EF framework versions, here we only need to automatically generate the LovePicture_DbContextConstructorDelete it and add another constructor:
1 public LovePicture_DbContext(DbContextOptions<LovePicture_DbContext> options) : base(options) { }
In this way, DbContext is provided to the project introducing this class library as an injection service. We only needStartup. csFileConfigureServicesMethod to add dependency injection:
1 // Add the database context 2 services. addDbContext <LovePicture_DbContext> (B => 3 {4 5 var dbLink = Configuration. getSection ("MoSelfSetting: DbLink "). value; 6 if (string. isNullOrWhiteSpace (dbLink) {throw new Exception ("no database link found. ");} 7 8 B. UseSqlServer (dbLink); 9 10 });
Here, a connection string is required for connecting to the database, which is passed through the UseSqlServer Extension Method of DbContextOptionsBuilder. The source of the string is configured in appsettings. json Configuration file, so it is convenient to use Configuration. getSection ("MoSelfSetting: DbLink "). value to read the connection string configured in the configuration file. Of course, if you can, you can write the connection string directly here. The hierarchical relationship of the configuration file is shown here:
With the above configuration, we can use DbContext In the MVC Controller. Here we use the constructor injection method:
1 private readonly LovePicture_DbContext _db;2 public HomeController(LovePicture_DbContext db)3 {4 _db = db;5 }
DbContext can be used in the Controller. In the Action, we can directly execute read/write commands on the database through various EF operation methods;
Use custom configuration information through IOptions <T>
Because the content in the following article involves information such as the user's upload profile picture, you need some configurable information (such as the upload path and link string ), therefore, we need to read the custom configuration node information. Here we use the ready-made appsettings. json file to configure information. Here, my configuration content is as follows:
1 {2 "Logging": {3 "IncludeScopes": false, 4 "LogLevel": {5 "Default": "Warning" 6} 7}, 8 "MoSelfSetting ": {9 // image content path 10 "UpHeadPhotoPath": "D :\\ F \ learning \ vs2017 \ netcore \ LovePicture. web \ wwwroot \ upfile \ headphoto ", 11" ViewHeadPhotoPath ":"/upfile/headphoto ", 12 // Avatar path 13" UpContentPhotoPath ":" D: \ F \ learn \ vs2017 \ netcore \ LovePicture. web \ wwwroot \ upfile \ contentphoto ", 14" ViewContentPhotoPath ":"/upfile/contentphoto ", 15 // email template 16" EmailTplPath ":" D: \ F \ learn \ vs2017 \ netcore \ LovePicture. web \ wwwroot \ tpl ", 17 // link string 18" DbLink ":" Server = 127.0.0.1, 1431; User Id = sa; Password = 123123; Database = LovePicture. db; "19} 20}
To get the custom information of this file, we need to create an object MoSelfSetting with the corresponding property name:
1 /// <summary> 2 /// custom configuration 3 /// </summary> 4 public class MoSelfSetting 5 {6 /// <summary> 7 // Avatar image Storage address 8 /// </summary> 9 public string UpHeadPhotoPath {get; set;} 10 11 /// <summary> 12 // Avatar image access address 13 /// </summary> 14 public string ViewHeadPhotoPath {get; set ;} 15 16 /// <summary> 17 // content image storage address 18 /// </summary> 19 public string UpContentPhotoPath {get; set ;} 20 21 /// <summary> 22 // view the content image save address 23 /// </summary> 24 public string ViewContentPhotoPath {get; set ;} 25 26 /// <summary> 27 // mail template folder path 28 /// </summary> 29 public string EmailTplPath {get; set ;} 30 31 /// <summary> 32 // database link 33 /// </summary> 34 public string DbLink {get; set;} 35}
The object class attribute name is the same as the node name in the appsettings. json file. Then, add the configuration file settings in the ConfigureServices method:
1 // set custom Configuration information 2 services. Configure <MoSelfSetting> (Configuration. GetSection ("MoSelfSetting "));
You only need to use this code to convert the data from the json configuration file to the object data, which is much more convenient than before. Then, you can also use this code in the Controller.IOptions <T>To inject the configuration file to the Controller:
1 private readonly LovePicture_DbContext _context; 2 private readonly MoSelfSetting _selfSetting; 3 private readonly IMemoryCache _cache; 4 5 public MemberController(LovePicture_DbContext context, IOptions<MoSelfSetting> selfSetting, IMemoryCache cache) 6 { 7 _context = context; 8 _selfSetting = selfSetting.Value; 9 _cache = cache;10 }
Finally, use IOptions <T>. the Value method can directly obtain the Entity Data with configuration file information. Test Cases are no longer written here, which will be used in the following sections, I hope this article will give you a better result. If you can, click "like". Thank you.