CodeFirst builds the Asp. Net Core2.0 website from scratch, codefirstcore2.0
Step by step, we will teach you how to build an Asp. Net Core2.0 website. All of the following are built in the. NETCore2.0 environment.
Right-click solution> Create Project>
Select Web> ASP. NETCoreWeb application (. NET Core)
Select a Web application. Currently, Docker is not enabled. for authentication, select personal user account (a series of user authentication code is automatically generated)
The Directory of the generated code levels is as follows:
It includes the implementation of identity information, such as related entity information (user). If you want to expand the user entity class automatically generated by Microsoft, you can expand it under ApplicationUser in Models, add attributes to this ApplicationUser: for example, add the WeChatId attribute, as shown below:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Identity;namespace DotNetCore20.Web.Models{ // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { /// <summary> /// Id /// </summary> public string WeChatId { get; set; } }}
After generation and migration, the database's AspNetUsers will have more WeChatId attributes.
I. Installation Reference
When the nugnet recovery reference is invalid, you can enter:
Dotnet restoreYou can.
After the recovery command is executed, a Microsoft. VisualStudio. Web. CodeGeneration. Design error is reported in NuGet. The information is as follows:
". NETPortable, Version = v0.0, Profile = Profile259 ,. NETFramework, Version = v4.6.1 "instead of the project target framework". NETCoreApp, Version = v2.0 "restored the package" Microsoft. composition 1.0.27 ". This may cause compatibility issues.
This library is a code generation tool for ASP. NET Core. The dotnet-aspnet-codegenerator command is used to generate controllers and views. You can uninstall the command without affecting project running.
The following methods can be used to reference a project Class Library:
1. Install Nuget (Official Website https://www.nuget.org/packages)
2. Right-click the dependency and choose add reference from the menu.
3. You can enter:Install-Package reference class library name
4. You can right-click the csproj project file to add it, and then executeDotnet restore
2. Create an object assembly
Right-click solution> Add project>
First, create an abstract class for Entity object inheritance. It mainly provides public attributes for each object.
Using System; using System. collections. generic; using System. componentModel. dataAnnotations; using System. runtime. serialization; using System. text; namespace dotnetcoreincluentity. core {// <summary> // DB Table Base /// </summary> [Serializable] public abstract partial class BaseEntity {// <summary> // Id /// </summary> [DataMember] public long Id {get; set ;}//< summary> /// database resource version /// </summary> 1502557027 public byte [] RowVersion {get; set ;} /// <summary >/// creation time /// </summary> [DataMember] public DateTime CreateTime {get; set ;} /// <summary >/// Update Time /// </summary> [DataMember] public DateTime UpdateTime {get; set ;} /// <summary >/// status /// </summary> [DataMember] public EnumState State {get; set ;}} /// <summary> /// status /// </summary> public enum EnumState {// <summary> /// Delete /// </summary> Delete = 1, /// <summary> // Normal // </summary> Normal = 0 ,}}
Add a UserExtend user extension class (Entity ):
Using dotnetcorepolicentity. core; using System. runtime. serialization; namespace dotnetcoreincluentity {[DataContract] public class UserExtend: BaseEntity {// <summary> /// user ID /// </summary> [DataMember] public long UserId {get; set ;}/// <summary >/// NickName /// </summary> [DataMember] public long NickName {get; set ;}}}
3. Create a data layer
Add reference
The DAL layer needs to use the EF Entity ing and the UserExtend Entity table in the Entity defined above. Therefore, you need to add references such as dotnetcoreentity and Microsoft. EntityFrameworkCore. Tools.
Shortcut: Ctrl + Alt + o open the package manager and enter the following:
Install-package Microsoft. EntityFrameworkCore. Tools
If the download fails due to network restrictions, we recommend that you change the nuget image to a blog garden resource by using the following method:
Right-click solution> Manage the nuget package of the solution. The following is displayed:
Create a data context class. The directory structure is as follows:
The internal code of DotNetCoreDbContext is changed to the following:
using DotNetCore20.Entity;using Microsoft.EntityFrameworkCore;namespace DotNetCore20.DAL.DbContext{ public class DotNetCoreDbContext : Microsoft.EntityFrameworkCore.DbContext { public DotNetCoreDbContext(DbContextOptions<DotNetCoreDbContext> options) : base(options) { } public DbSet<UserExtend> UserExtend { get; set; } }}
The basic entity ing-related code is complete, and now there is another step, that is, the configuration of the database connection string.
First open the appsettings. json file and add the following under the ConnectionStrings node:
Copy codeThe Code is as follows: "DotNetCoreConnection": "Server = (localdb) \ mssqllocaldb; Database = DotNetCoreDb; Trusted_Connection = True; MultipleActiveResultSets = true"
The added parameters are as follows:
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDefaultDb;Trusted_Connection=True;MultipleActiveResultSets=true", "DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }}
Open the Startup File under the web site and add the following lines in the ConfigureServices method:
// Custom database connection string services. AddDbContext <DotNetCoreDbContext> (options => options. UseSqlServer (Configuration. GetConnectionString ("DotNetCoreConnection ")));
The added parameters are as follows:
Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using Microsoft. aspNetCore. builder; using Microsoft. aspNetCore. diagnostics. entityFrameworkCore; using Microsoft. aspNetCore. identity; using Microsoft. aspNetCore. http; using Microsoft. entityFrameworkCore; using Microsoft. aspNetCore. hosting; using Microsoft. extensions. configuration; using Microsoft. extensions. depende NcyInjection; using Microsoft. extensions. options; using dotnetcoreappsweb. data; using dotnetcoreappsweb. models; using dotnetcoreappsweb. services; using dotnetcoremongodal. dbContext; namespace dotnetcoreappsweb {public class Startup {public Startup (IConfiguration configuration Configuration) {configuration = Configuration;} public IConfiguration configuration {get;} // This method gets called by the runtime. use this Method to add services to the container. public void ConfigureServices (IServiceCollection services) {services. addDbContext <ApplicationDbContext> (options => options. useSqlServer (Configuration. getConnectionString ("DefaultConnection"); // custom database connection string services. addDbContext <DotNetCoreDbContext> (options => options. useSqlServer (Configuration. getConnectionString ("DotNetCoreConnection"); services. addId Entity <ApplicationUser, IdentityRole> (). addEntityFrameworkStores <ApplicationDbContext> (). addDefaultTokenProviders (); // Add application services. services. addTransient <IEmailSender, AuthMessageSender> (); services. addTransient <ISmsSender, AuthMessageSender> (); services. addMvc ();} // This method gets called by the runtime. use this method to configure the HTTP request pipeline. public void Config Ure (IApplicationBuilder app, IHostingEnvironment env) {if (env. isDevelopment () {app. usemediaexceptionpage (); app. useBrowserLink (); app. useDatabaseErrorPage ();} else {app. useExceptionHandler ("/Home/Error");} app. useStaticFiles (); app. useAuthentication (); app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller = Home}/{action = Index}/{id ?} ");});}}}
Run the program and Click Log On (any operation required to access the database). The error page is displayed:
Click application migration to automatically migrate the database.
Because the two databases only automatically migrate the user's table AspNetUsers,
Therefore, you have to run commands in the package manager in VS for migration.
Add-Migration firstMigration-Context DotNetCoreDbContext
Run the preceding command and then run the following command:
Update-Database-ContextDotNetCoreDbContext;
Check the database and you will find two more databases,
Take DotNetCoreDefaultDb as an example to generate the following table:
The AspNetUsers contains the previously added WeChatId field.
Then run the program again:
Such a complete Asp. NetCore2.0 website is initially running.
In the next article, Repository and UnitWorks will be added at the DAL layer to achieve unified management of simple crud.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.