Apworks Framework practice (6): using the Entity Framework-based warehouse infrastructure, apworksentity

Source: Internet
Author: User
Tags microsoft sql server management studio

Apworks Framework practice (6): using the Entity Framework-based warehouse infrastructure, apworksentity

In the previous chapter, we have designed a simple domain model. Next we hope to realize the persistence and query of the domain model. Apworks provides the warehousing infrastructure for Entity Framework, nhib.pdf, and MongoDB. This section describes how to use the Entity Framework-based Warehousing mechanism in Apworks.

Build an Entity Framework-based infrastructure

Before using the warehousing service provided by Apworks, we need to build an Entity Framework-based infrastructure so that the following Apworks can use these infrastructure functions, the Entity Framework is used to manage the lifecycle of Domain Model objects.

Starting from DbContext

We adopt the Entity Framework Code First programming model. Therefore, we will start with DbContext to prepare for the use of the Entity Framework warehousing mechanism.

First, right-click the EasyMemo. Repositories project and choose manage NuGet packages. In the "manage NuGet package" text box that appears, enter the keyword "apworks ]. In the filtered list, find Apworks. Repositories. EntityFramework, and click Install.

Note: To install this package, you will also install the packages it depends on in the EasyMemo. Repositories project. These packages include:

  • Apworks 2.5.5662.20.15
  • Castle. Core 3.3.1
  • EntityFramework 6.1.1

Next, in the EasyMemo. Repositories project, create a class named EasyMemoContext, which is inherited from the System. Data. Entity. DbContext class. The Code is as follows:

public class EasyMemoContext : DbContext{    public EasyMemoContext()        : base("EasyMemoDB")    {            }    public DbSet<Account> Accounts { get; set; }    public DbSet<Role> Roles { get; set; }    public DbSet<Memo> Memos { get; set; }}

This is the usage of standard Entity Framework Code First. However, we recommend that you only define the DbSet attribute for the aggregation root in Apworks best practices, so that the definition of DbContext can be very concise and intuitive.

The next step is to define some types/database mappings for entities in the domain model. According to the standard Entity Framework usage, we can define a series of subclasses inherited from the EntityTypeConfiguration generic class, and define the ing rules in these subclasses, in the OnModelCreating method of EasyMemoContext, add the instances of these subclasses to the mappings set. Alternatively, you can directly define the ing rules in the OnModelCreating method. I still prefer the previous method, that is, to create a subclass that inherits the EntityTypeConfiguration for each object that needs to be configured for ing. Although there may be many additional class definitions, but this will make the code structure more readable. For example, for the Account object, we can define the ing configuration type as follows:

public class AccountEntityConfiguration : EntityTypeConfiguration<Account>{    public AccountEntityConfiguration()    {        ToTable("Accounts");        HasKey(x => x.ID);        Property(x => x.ID)            .IsRequired()            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);        Property(x => x.DateCreated).IsRequired();        Property(x => x.DateLastLogon).IsOptional();        Property(x => x.DisplayName)            .IsRequired()            .IsUnicode()            .HasMaxLength(32);        Property(x => x.Email)            .IsRequired()            .IsUnicode()            .HasMaxLength(64);        Property(x => x.IsDeleted).IsOptional();        Property(x => x.Name).IsRequired()            .IsUnicode()            .HasMaxLength(16);        Property(x => x.Password).IsRequired()            .IsUnicode()            .HasMaxLength(4096);    }}

Then, add the instance of this class to the OnModelCreating overload method:

protected override void OnModelCreating(DbModelBuilder modelBuilder){    modelBuilder.Configurations.Add(new AccountEntityConfiguration());}

OK. Next, use a similar method to define the ing configuration class for the necessary entity types in the domain model, and add the instances of these classes to the OnModelCreating overload method in sequence. The code is not listed here. You can click the download link at the end of this section to download the source code to your local device for reference.

Set database initialization policies

Entity Framework supports the following database initialization policies:

In practical applications, we can directly use the above Database initialization policies. When the Initialize method of the Database object is called, the Entity Framework initializes the database based on the selected initialization policy and the above ing configuration information. For demonstration purposes, we hope to prepare some data for database initialization so as to introduce future content. Therefore, we can customize a set of database initialization policies, and write the required data into the database.

First, create a new class named DatabaseInitializeStrategy in the EasyMemo. Repositories project and inherit the DropCreateDatabaseIfModelChanges type:

public class DatabaseInitializeStrategy     : DropCreateDatabaseIfModelChanges<EasyMemoContext>{}

Then, reload the Seed method in this type and add the following code:

Public class DatabaseInitializeStrategy: DropCreateDatabaseIfModelChanges <EasyMemoContext> {protected override void Seed (EasyMemoContext context) {var adminPermission = new Permission {Privilege = Privilege. systemAdministration, Value = PermissionValue. allow}; var administrators = new Role {Name = "System Administrator", Description = "a group of accounts that execute system management tasks ", permissions = new List <Permission> {adminPermission}; var administrator = new Account {DateCreated = DateTime. utcNow, DisplayName = "Administrator", Email = "admin@easymemo.com", Name = "admin", Password = "admin", Roles = new List <Role> {administrators}; context. accounts. add (administrator); base. seed (context );}}

Therefore, we have our own database initialization policy. The next step is to use this policy in the EasyMemo system.

Run our code

Open the EasyMemo. Services Project, and add a reference to the Apworks. Repositories. EntityFramework package through the manage NuGet Package function. Then, under the Appp_Start directory, create a class named DatabaseConfig:

The code for this class is as follows:

public static class DatabaseConfig{    public static void Initialize()    {        Database.SetInitializer(new DatabaseInitializeStrategy());        new EasyMemoContext().Database.Initialize(true);    }}

Next, open the Global. asax. cs file under the EasyMemo. Services Project and add a call to DatabaseConfig. Initialize to the Application_Start method:

public class WebApiApplication : System.Web.HttpApplication{    protected void Application_Start()    {        GlobalConfiguration.Configure(WebApiConfig.Register);        DatabaseConfig.Initialize();    }}

Open the web. config file of the EasyMemo. Services Project, find the entityFramework node, and configure the node so that the Entity Framework can use the SQL Server database you specified:

<entityFramework>  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">    <parameters>       <parameter value="Data Source=localhost; Initial Catalog=EasyMemoDB; Integrated Security=True; Connect Timeout=120; MultipleActiveResultSets=True" />    </parameters>  </defaultConnectionFactory>  <providers>    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />  </providers></entityFramework>

Now, set [EasyMemo. services] the project is set to start the project, and then press F5. Wait a moment. When the following screen appears in the browser, we can find the database automatically generated by Entity Framework in SQL Server:

 

Open Microsoft SQL Server Management Studio and connect to the configured database instance. We can see that EasyMemoDB is displayed in the Database List:

 

We can also query our prepared data:

The database structure automatically generated by Entity Framework is as follows:

Of course, we do not need to pay too much attention to this data model currently. After all, we do not plan to program databases.

Start to use the Entity Framework-based Apworks warehousing Service

Before using the Apworks warehousing service, we must first configure the entire Apworks runtime environment. Based on the previous layered structure, EasyMemo. Services is a RESTful API project on the server side, which is implemented by ASP. NET Web API 2.0. Therefore, the configuration for the Apworks framework runtime environment also occurs in this project. To enable the Web API controller to obtain Apworks warehousing and context instances, we adopt IoC technology and select Microsoft Unity as the dependency injection framework, this is the only dependency injection framework currently supported by the Apworks framework. Of course, the dependency Injection System of Apworks can be expanded. You can expand the dependency Injection System Based on your project needs so that it can support multiple mainstream dependency injection frameworks.

Configure the Apworks Runtime Environment

First, use manage NuGet packages to add the following package references to the EasyMemo. Services Project:

Next, create a static class named ApworksConfig in the App_Start folder of the EasyMemo. Services project, as shown in the following figure:

using Apworks.Application;using Apworks.Config.Fluent;using Apworks.Repositories;using Apworks.Repositories.EntityFramework;using EasyMemo.Repositories;using Microsoft.Practices.Unity;using Unity.WebApi;public static class ApworksConfig{    public static void Initialize()    {        AppRuntime            .Instance            .ConfigureApworks()            .UsingUnityContainerWithDefaultSettings()            .Create((sender, e) =>            {                var unityContainer = e.ObjectContainer.GetWrappedContainer<UnityContainer>();                unityContainer.RegisterInstance(new EasyMemoContext(), new PerResolveLifetimeManager())                    .RegisterType<IRepositoryContext, EntityFrameworkRepositoryContext>(                        new HierarchicalLifetimeManager(),                        new InjectionConstructor(new ResolvedParameter<EasyMemoContext>()))                    .RegisterType(typeof (IRepository<>), typeof (EntityFrameworkRepository<>));                GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(unityContainer);            })            .Start();    }}

Note: The Fluent Interface configuration method is used here. Apworks also supports web. config/app. config-based configuration. I will introduce this part in the future.

Then, In the Application_Start method of the Global. asax. cs file, call the above Code:

public class WebApiApplication : System.Web.HttpApplication{    protected void Application_Start()    {        GlobalConfiguration.Configure(WebApiConfig.Register);        DatabaseConfig.Initialize();        ApworksConfig.Initialize();    }}

OK. The Apworks runtime environment configuration is basically complete. Next, let's create a simple RESTful API to run the entire process.

Start our ASP. NET Web API journey

In the EasyMemo. Services Project, find the Controllers directory, right-click, and choose add> controller from the context menu ]. In the dialog box that appears, select Web API 2 Controller-null ]:

In the "add controller" dialog box, enter "AccountsController" in the "Controller name" column ]:

After you click Add, Visual Studio opens the code editing interface of AccountsController. In this case, you can add the following code to the AccountsController class:

[RoutePrefix("api/accounts")]public class AccountsController : ApiController{    private readonly IRepository<Account> accountRepository;    private readonly IRepositoryContext unitOfWork;    public AccountsController(IRepositoryContext unitOfWork, IRepository<Account> accountRepository)    {        this.accountRepository = accountRepository;        this.unitOfWork = unitOfWork;    }    [HttpGet]    [Route("name/{name}")]    public IHttpActionResult GetByName(string name)    {        var account = this.accountRepository.Find(Specification<Account>.Eval(acct => acct.Name == name));        if (account != null)        {            return Ok(new            {                account.Name,                account.DisplayName,                account.Email,                account.DateCreated,                account.DateLastLogon            });        }        throw new Exception(string.Format("The account '{0}' does not exist.", name));    }    protected override void Dispose(bool disposing)    {        if (disposing)        {            unitOfWork.Dispose();        }        base.Dispose(disposing);    }}

Is the code concise? Let's start EasyMemo again. services: set this project as a startup project, and press F5 directly. On the 403.14-Forbidden page that is the same as above, enter:

http://localhost:30295/api/accounts/name/admin

Now you can see the result returned by this RESTful API: it returns the details of the account admin:

Summary

This article describes in detail how to use Entity Framework in the Apworks Framework and provide the infrastructure of warehousing and context for an ASP. NET Web API RESTful service. Starting from the next lecture, we will focus on all aspects of ASP. NET Web API implementation, including Exception Handling, authentication and authorization, and data transmission objects and view models.

Source code download

Click here to download the EasyMemo solution source code as of this article.

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.