NET Core & Entity Framework Core

Source: Internet
Author: User
Tags app service xunit

This article is the ABP Official document translation version, translated based on the 3.2.5 version

Official documents in four parts

First, the tutorial document

Ii. ABP Framework

Three, Zero module

Iv. Other (Chinese translation resources)

This is the first part of this article.

The first part is divided into three articles

1-1 hand-introduced door

1-2 Advanced

1-3 Miscellaneous (related theoretical knowledge)

The first article contains two steps.

1-1-1 ASP & Entity Framework core back-end (core) with two (second link)

1-1-2 ASP. NET MVC, Web API, EntityFramework & AngularJs Front End

Now enter the text

Create n-tier Web applications using ASP. NET Core, Entity Framework Core and ASP. NET boilerplate

Twotooth achyranthes root Quotations:Halil Ibrahim Kalkan, Jul

Here is a hands-on portal tutorial, creating a Web application based on ASP. NET Core, Entity framework Core, ABP Framework, PS: Self-test module with automatic.

    • Sample download (please help yourself on GitHub)

This article is in the following directory:

Introduced

Pre-preparation

Create an App

Formal development

Create Task Entity Entities

Add a task to the database context DbContext

Create a First Data migration

Create a database

Writing Task Services

Test Task Service

Task List Display

Add Menu

Creating task controllers and view models

Task List Page

Localization

Task Filter

Automated testing of Task list pages

Other related content

Article Revision history

All rights reserved

Introduced

This is the first part of a series of articles: Create n-tier Web applications using ASP. NET Core, Entity Framework Core and ASP. NET boilerplate

In this article, I'll guide you through creating a sample (a cross-platform, multi-tiered Web application) that uses the following tools (readers should be prepared in advance):

    • Net Core Cross-Platform Application Foundation development Framework
    • Base framework templates for ASP. NET boilerplate (ABP) development
    • ASP. NET Core Web development Framework
    • Entity Framework Core ORM Data Framework
    • Twitter Bootstrap HTML&CSS Front-end development framework
    • JQuery Client Ajax/dom Class Library
    • XUnit and shouldly service-side test tools (unit test/integration test)

Log4net and AutoMapper are used by default in the ABP framework.

We also use the following technologies:

    • Layered Architecture Layered Architecture
    • Domain driven Design (DDD) DDD domain model
    • Dependency injection (DI) di dependency injection
    • Integration Testing Integration Test

The demo development Project is a simple task management application that allocates tasks. I'm not going to develop it one layer at a--it's the level you need to switch directly as the app expands. As the app pushes, I'll describe the features required for the ABP and other frameworks.

Pre-preparation

The following tools are required for the development of the sample, please install it on your machine in advance:

    • Visual Studio 2017
    • SQL Server (You can change the connection string to LocalDB)
    • Visual Studio Extensions:
      • Bundler & Minifier
      • Web Compiler
Create an App

First Use the ABP template (http://www.aspnetboilerplate.com/Templates) to create a web App project named "Acme.simpletaskapp". When you create a template, you can set your own company name (such as Acme).

This sample uses the MPa (Multi page Web application) Multi-page mode (note: That is, using MVC and razor Technology) for development, this article does not use SPA (Note: Twotooth achyranthes root spa is using angular) single page mode. In order to use the most basic development template features, the Module zero module is not used in this article.

The ABP template creates a multi-tiered solution, such as:

The template automatically creates 6 items based on the name you enter.

    • Core domain layer/business layer, including entity entities, Domain Services domain service, etc.
    • Application application layer, including DTOs, application Services application service, etc.
    • Entity Framework infrastructure layer, EF core Database integration processing (EF core abstracted from other layers)
    • Web presentation layer, the ASP. NET MVC Layer
    • Tests unit Testing and integration testing, including application layer, domain layer, infrastructure layer, without Web presentation layer
    • Web.tests ASP. NET core integration test, including all integration tests for the Web presentation layer

These are the results of a project without a zero selection, and if you choose Zero, the project structure will become:

When you run the app, you'll see the user interface shown:

This app contains a top-level menu bar with empty home page, about pages, and a drop-down option for a language.

Formal development Create task entities entity

We start by creating a simple task entity, the project object, as it belongs to the domain layer and adds it to the core program.

The code is as follows:

View Code

    • The Task entity inherits from the entity base class of the ABP, and the entity base class default ID attribute is of type int. If the primary key type is a non-int type, you can also select the Entity<tprimarykey> version of the model;.
    • Ihascreationtime is a simple interface that defines only the CreationTime attribute (the name of the Unified specification CreationTime)
    • The Task entity defines a required Title and non-required Description
    • Taskstate is a simple enumeration that defines the state of task tasks
    • Clock.now returns the default DateTime.Now. But it provides an abstract approach that allows us to easily convert to Datetime.utcnow when needed in the future. Always use Clock.now in the ABP framework instead of using DateTime.Now.
    • The Task entity is stored in the Apptasks table of the database.

Add a task to the database context DbContext

. The Entityframeworkcore contains a pre-defined DbContext. Add the DbSet of the Task entity to the DbContext.

The code is as follows:

View Code

Now, EF Core knows that we have a Task entity.

Create a First Data migration

We will create an initialization database migration file that will automatically create the database and database table Apptasks. Open Source Manager Package Manager Console from Visual Studio, execute the add-migration command (the default project must be. Entityframeworkcore project),

This command will be in. Under the Entityframeworkcore project, create a migration (migrations) folder that contains a snapshot of the migration class and the database model.

The initialization (Initial) Migration class is automatically created as shown in the following code:

View Code

When we execute the Database Migration command, the code creates the Apptasks table (see the Entity Framework documentation for more migration related information)

Create a database

After the migration is complete (note: After the add-migration command executes), execute the update-database command in the package management console, such as:

This command creates a database named "simpletaskappdb" in local SQL Server and performs a database migration (at this point we have only one "initialize (Initial)" migration):

Now that we have the task entity and we have the corresponding database tables in the database, we enter some simple tasks into the table.

Friendly tip: The database context string connection string in the. Web App's Appsettings.json. (To change the database itself to change the string oh).

Writing Task Services

The Application Services Application Layer service is used to expose domain business logic to the presentation layer. The presentation layer invokes an application service by using the data Transfer Object Data Transfer Objects (DTO) action parameter when necessary, and the application service executes some specific business logic by invoking the domain object and returns a DTO to the presentation layer when needed.

We're in. The first app service Taskappservice is created in the Application project, which executes the application logic associated with the task. First, we'll define an app service interface:

The code is as follows:

View Code

We recommend defining the interface first, but not the other way. As a rule, all application services in the ABP need to implement the Iapplicationservice interface (it is just an empty token interface). We created a GetAll method to query the task list, and we defined the following DTOs:

The code is as follows:

View Code
    • The Getalltasksinput DTO defines an input parameter for the GETALL application service method. We define the status state as a DTO object and not as a parameter to the method. This will allow us to add additional parameters to this dto in the future, and to be compatible with existing clients (we can, of course, add a state parameter to the method).
    • Tasklistdto returns the task data with open. The DTO inherits from Entitydto, and entitydto simply defines the id attribute (we can add the ID to our DTO without inheriting the entitydto). We have defined [Automapfrom] attributes to create AutoMapper Auto Map task entity to Task List Dto tasklistdto. This feature is defined in the Abp.automapper nuget package.
    • Listresultdto is a simple class that contains a list (we can return a list of list<tasklistdto> directly).

Now, we can implement the Itaskappservice.

The code is as follows:

View Code

    • Taskappservice This class inherits from Simpletaskappappservicebase, Simpletaskappappservicebase (from ABP applicationservice Class inheritance) has been generated automatically in the template. Taskappservice does not have to inherit from Simpletaskappappservicebase, app service can be a normal class. But the Applicationservice base class has some pre-injected services (like the objectmapper used here)
    • We use the dependency injection dependency injection to get the data warehousing repository
    • Repositories data warehousing is used to abstract database operations for data entities. The ABP creates pre-defined database warehouses for each entity (as is used here in irepository<task>) for common tasks. The Irepository.getall () method is used to query the data entity, which returns a IQueryable interface.
    • Whereif This is an extension method in the ABP, which provides a simple conditional syntax for a iqueryable.where method.
    • Objectmapper used to map the Task object list to the Task List Dto object list (based on the application Service base class and implemented by default AutoMapper)

Test Task Service

In creating the user interface money, we need to test the Task app service Taskappservice. If you are not interested in automated testing, you can ignore this section.

Our templates are included. Tests project, which can test our code. Instead of using a SQL Server database, this project uses EF Core's in-memory database. So, we can do unit testing without a real database. It creates a separate database for each test. So each test is isolated. We need to use the Testdatabuilder class to add the initial test data to the in-memory database before starting the test. I modified the testdatabuilder.

The code is as follows:

View Code

Through the sample project source code, you can understand testdatabuilder where to use, how to use. We add 2 tasks (one already completed) to the database context DbContext. We can assume that there are 2 tasks in the database and start writing test cases. The first inheritance test is used to test the Taskappservice.getall method.

The code is as follows:

View Code

We created 2 different test cases to test the GetAll method. Now we open the test browser (under the Test\windows\test Explorer menu in the VS Main Menu) and start the unit test.

All tests were successful. The last one we can now ignore it, he is a template-generated test.

Friendly tip: ABP templates are installed by default using XUnit and shouldly. We use them to write our tests.

Task List Display

Now we are sure that the Taskappservice service will work. We can start creating pages to show all the tasks.

Add Menu

First, we add a new menu to the top-level menu

The code is as follows

View Code

The template comes with two pages: first page and about page, as shown in the code above. We can also modify them to create a new page. But now we don't modify the homepage and about the page, we create a new menu item.

Creating task controllers and view models

We're in. Under the Web project, create a new controller class named Taskscontroller.

The code is as follows

View Code
    • Taskscontroller inherits from Simpletaskappcontrollerbase (Simpletaskappcontrollerbase inherited from Abpcontroller), which contains the application Controllers The common base code required.
    • We reflected the itaskappservice to get to all the task lists.
    • We're in. A Indexviewmodel class is created in the WEB project to present the data to the view so that the results of the GetAll method are not directly exposed to the view.

The code is as follows

View Code

We created a simple view model, and in its constructor we got a list of tasks (provided by Itaskappservice). It also has a Gettasklabel method for labeling tasks in a view with a select Bootstrap tag.

Task List Page

Finally, complete the actual Index view.

The code is as follows

View Code

We use the Bootstrap List group component and the well-defined model to render the view. We use the Indexviewmodel.gettasklable () method to get the label type of the task. After rendering the interface such as:

Localization

We use the L method that comes with the ABP framework in the view. It is used for localizing languages. We're in. A localized string is defined in the Localization/source folder under the Core project, using a. json file. Localized language settings for the English version

The code is as follows

View Code

The template comes with most of the text, and of course, they can be deleted. In the above code I just added the last three lines. Localization using ABP is fairly straightforward and if you want to learn more about localization systems, consult the documentation localization document

Task Filter

As I said before, Taskcontroller actually uses getalltasksinput, which allows you to filter tasks flexibly. We can add a drop-down menu of task lists to filter tasks. First, we add a drop-down menu to the view (we add to the header):

The code is as follows

View Code

Then I modified the Indexviewmodel, adding the Seletedtaskstate attribute and the Gettaskstateselectlistitems method:

The code is as follows

View Code

We can also set the Selectedtaskstate in the controller:

The code is as follows

View Code

Now that we run the program, we can see a drop-down box in the upper-right corner of the view.

We added a drop-down box, but it's not available yet. We need to write some simple JavaScript code to re-request/Refresh the Task List page after the drop-box content changes. We're in. The wwwroot\js\views\tasks\index.js file was created in the WEB project

The code is as follows

View Code

We first add the bundler & minifier Extension (which is the zip file that the ASP. NET Core item targets) to compress the size of the script, and then start writing JavaScript in the view:

This will be in the. Add the following code to the Bundleconfig.json in the WEB project

The code is as follows

View Code

A compressed version of script was created at the same time

Whenever I change the index.js, the index.min.js will automatically regenerate. Now we can insert a JavaScript file on our page.

The code is as follows

View Code

At this point, our view will use the Index.js package in the development environment, and the Index.min.js (compressed version) package in the production environment. This is a common practice in the ASP. NET Core MVC project.

Automated testing of Task list pages

An inheritance test module is integrated in the ASP. NET Core MVC framework. We can test our service-side code in full. If you are not interested in automated testing, you can ignore this section.

The ABP template comes with. Web.tests Project. We create a normal test to request Taskcontroller.index, and then check the feedback content:

The code is as follows

View Code

Getresponseasstringasync and GetUrl are useful methods in the Abpaspnetcoreintrgratedtestbase class of ABP. Using these quick methods we can make it easier to create a request, which is relatively complex if you use the client request directly (an HttpClient instance). For further information, refer to the Integration testing documentation for ASP.

When we start the Debug test module, we can see the feedback of the HTML as

It is normal to show feedback on the Index page. However, we would like to know if the HTML returned is as we expected. There are many class libraries that can be used to parse HTML. of the ABP template. The Web.tests Project pre-installs one of these class libraries Anglesharp we use it to examine the HTML code that was created.

The code is as follows

View Code

You can drill down into HTML for more details. But in general, checking the basic label is enough.

Other related content

The second Second article then develops the application service.

(second translation link)

Article Revision history
    • 2017-07-30: Replace the listresultoutput in the article with the Listresultdto
    • 2017-06-02: Modify articles and solutions to support. NET Core
    • 2016-08-08: Add a link to the second article
    • 2016-08-01: First Release
All rights reserved

The copyright of the article and any source code and files therein belongs to the code Project Open License (Cpol) all

NET Core & Entity Framework Core

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.