MVC Core website development (Ninesky) 2.1, the foreground of the topic, mvcninesky

Source: Internet
Author: User

MVC Core website development (Ninesky) 2.1, the foreground of the topic, mvcninesky

The topic model was created last time. This time, the topic is displayed at the front end. It involves the data storage layer, business logic layer, and Web layer. Use the migration, update the database, and inject some content.

1. Add a data storage layer. 1. Add Ninesky. DataLibrary (same as the method added last time)

InSolution (Ninesky)Right-clickAdd->Create a project

Select.NET Core->Class Library (. NET Core)

Name input:Ninesky. DataLibrary(The data access and storage function is implemented in this project) 2. AddEntityFrameworkCore package

InNinesky. DataLibraryProjectReferenceRight-clickManage NuGet packages.

In the dialog box, selectBrowseTag, enter"EntityFrameworkCore", And then find"Microsoft. EntityFrameworkCoreClick Install.

ClickUpdateLabel, selectNETStandard. Library, PointUpdateTo version 1.6.1.

3. Single Data Query

Change the default Class1.cs generated in the project to BaseRepository. cs.

Add the following code:

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. threading. tasks; 5 using Microsoft. entityFrameworkCore; 6 7 namespace Ninesky. dataLibrary 8 {9 /// <summary> 10 // warehouse base class 11 /// </summary> 12 public class BaseRepository <T> where T: class 13 {14 private DbContext _ dbContext; 15 public BaseRepository (DbContext dbContext) 16 {17 _ dbContext = dbContext; 18} 19 20 // <summary> 21 // query 22 // </summary> 23 // <param name = "Id"> Primary Key </param> 24 /// <returns> Object </returns> 25 public T Find (int Id) 26 {27 return _ dbContext. set <T> (). find (Id); 28} 29} 30}
Ii. business logic layer

BackNinesky. BaseProject

1. Add a project reference

InReferenceRight-clickAdd reference.

 

Select"Ninesky. DataLibrary", Click OK

2. Column Service

Add the CategoryService class and add the Find method. The Code is as follows:

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. threading. tasks; 5 using Microsoft. entityFrameworkCore; 6 using Ninesky. dataLibrary; 7 8 namespace Ninesky. base 9 {10 /// <summary> 11 // column Service class 12 /// </summary> 13 public class CategoryService 14 {15 private BaseRepository <Category> _ baseRepository; 16 public CategoryService (DbContext dbContext) 17 {18 _ baseRepository = new BaseRepository <Category> (dbContext ); 19} 20 21 /// <summary> 22 // search for 23 /// </summary> 24 /// <param name = "Id"> topic Id </param> 25 // <returns> </returns> 26 public Category Find (int Id) 27 {28 return _ baseRepository. find (Id); 29} 30}
Iii. web layer implementation

BackNinesky. WebProject.

1. Installation Package reference

● Install the EntityFrameworkCore. SqlServer package

InNinesky. WebProjectReferenceRight-clickManage NuGet packages.

In the dialog box, selectBrowseTag, enter"EntityFrameworkCore", And then find"Microsoft. EntityFrameworkCore. SqlServer"Click to install.

Note:This package provides SQL Server database support

● Install the Microsoft. EntityFrameworkCore. Tool package

In the dialog box, selectBrowseTag, enter"Microsoft. EntityFrameworkCore. Tool", SelectIncluding the pre-release versionAnd then find"Microsoft. EntityFrameworkCore. ToolClick Install.

Note: This package supports data migration and database update.

2. Set the connection string

In vs2015, select View> SQL Server Object Manager.

There are two instances, MSSQLLocalDB and ProectsV13. both of them are SQL Server 13.0.2151. What is the difference.

In SQL ServerRight-click and choose>Add SQL Server

In the connection dialog box, selectMSSQLLocalDB(If you do not know the difference, simply select the first version without a version number.) Click Advanced.

Copy the connection string, open etettings. json, and add the connection string configuration (in the red box)

3. Add data context

InNinesky. Right-click a Web project and choose add> class,Input nameNineskyDbContext

InReferenceRight-clickAdd reference. Select"Ninesky. Base", Click OK

Open CategoryController, usingNinesky. Base,In this case, we found a phenomenon such:

The DataLibrary namespace is automatically displayed here. In this Web project, DataLibrary is not referenced, but onlyBase.BaseReferences the DataLibrary project. The reference is also contagious. I tried to uninstall the EntityFrameworkCore reference in the Base project and can also use the EntityFrameworkCore function normally ~ Ah ~~ Ah ~~~, Scream three times, simply do not reference EntityFrameworkCore in both the WEB Project and the Base project, as long as it is referenced in DataLibrary.

After completion, the code of NineskyDbContext is as follows:

  1 using Microsoft.EntityFrameworkCore;  2 using Ninesky.Base;  3   4 namespace Ninesky.Web  5 {  6     public class NineskyDbContext:DbContext  7     {  8         public DbSet<Category> Categories { get; set; }  9  10         public NineskyDbContext(DbContextOptions options):base(options) 11         { 12  13         } 14     } 15 } 16 

 

4. Injection NineskyDbContext

OpenStartup. csFile, inConfigureServicesMethod.

Services. AddDbContextMethod for InjectionDbContext;

Options => options. UseSqlServerIndicates thatSqlServerDatabase. (To connect to MySql, referenceEntityFrameworkCorePackage, and then hereOptions => options. UseMySql (......).

Configuration. GetConnectionString ("DefaultConnection ")Indicates reading the name from the configuration fileDefaultConnection.

5. Enable migration and database creation

● Enable migration

SelectTools->NuGet Package Manager->Package Manager Console

 

EnterAdd-Migration InitEnter

After completion, you can see thatMigrationsFolder, indicating that the migration is successfully enabled.

● Create a database.

Enter Update-Database in the Package Manager Console and press enter to create a Database.

You canSQL Server Object ManagerThe database and table are successfully created.

Note: database files are not created in projects by default. The downloaded code does not contain database files. Run the command on your own.Update-DatabaseCommand to create a database. In addition, the V13 version is SQL Server 2016, and I tested it on a machine that installs v12 (version 2014 ).Update-DatabaseYou can also create databases. Other versions have not been tried. It is estimated that the versions later than 08R2 will be okay.

6. Modify the Index method of the topic controller.

The next step is to return to CategoryController. cs and modify the Code as follows:

1 namespace Ninesky. web. controllers 2 {3 /// <summary> 4 // topic controller 5 /// </summary> 6 public class CategoryController: controller 7 {8 /// <summary> 9 // data context 10 /// </summary> 11 private NineskyDbContext _ dbContext; 12 13 /// <summary> 14 // topic service 15 /// </summary> 16 private CategoryService _ categoryService; 17 18 public CategoryController (NineskyDbContext dbContext) 19 {20 _ dbContext = dbContext; 21 _ categoryService = new CategoryService (dbContext ); 22} 23 24 // <summary> 25 // View column 26 // </summary> 27 // <param name = "id"> column Id </ param> 28 // <returns> </returns> 29 [Route ("/Category/{id: int} ")] 30 public IActionResult Index (int id) 31 {32 var category = _ categoryService. find (id); 33 if (category = null) return View ("Error"); 34 return View (category); 35} 36} 37} 38

Topic controller Constructor (Public CategoryController (NineskyDbContext dbContext)) There is a parameter NineskyDbContext, becauseStartup. csNineskyDbContext is injected, and this parameter is automatically obtained when the controller is initialized.

IndexMethod: Use categoryService to query the corresponding id column and return to the view.

7. Add an Index View

InViewsRight-click the folder and choose>Add->Create a folder,Input nameCategory

In the newly createdCategoryRight-click the folder and choose>Add->New item

SelectMVCAttempt page, namedIndex. cshtml

View after adding ....

It's really clean. There's nothing. To put it up, right-click on the Action to add a view. You can also generate code based on the model. Now, you have to write everything by yourself, which requires a lot of work. You can't write it on your own. Write a simple view

1 @ model Ninesky. base. category 2 @ {3 ViewData ["Title"] = Model. name; 4} 5 6 8. Insert a row of test data

InSQL Server Object ManagerTo view the Categories data,

Enter a data entry in the table.

 

Run F5. You can see that the data you just entered has been taken out. Here, the column type directly shows[Display (Name = "regular columns")]The value is indeed smart.

4. Other code hosting address: https://git.oschina.net/ninesky/Ninesky

Article published by: http://www.ninesky.cn

                 http://mzwhj.cnblogs.com/

Code package download: http://pan.baidu.com/s/1b2UI0e

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.