Apworks Framework Combat (VI): Using the Entity Framework-based warehousing infrastructure

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

In the previous chapters, we have designed a simple domain model, and then we want to be able to implement the domain model persistence and query. In Apworks, a warehousing infrastructure for the entity Framework, NHibernate, and MongoDB is implemented. In this section, I'll show you how to use the Entity Framework-based warehousing mechanism in Apworks.

Building an Entity Framework-based infrastructure

Before using the warehousing services provided by Apworks, we first need to build an Entity Framework-based infrastructure so that the next apworks can use these infrastructure features and leverage the entity The framework implements the management of the domain model object life cycle.

Starting from DbContext

We use the programming model of the Entity Framework Code first, so we'll start with DbContext and prepare for the use of the Entity Framework Warehousing mechanism.

First, right-click on the "Easymemo.repositories" project and select the "Manage nuget packages" option. In the pop-up manage NuGet package, in the Search online text box, enter the keyword "Apworks". In the filtered list, locate Apworks.Repositories.EntityFramework, and then click the Install button.

Description: Installing the package also installs the packages it relies on in a "Easymemo.repositories" project, which includes:

    • Apworks 2.5.5662.37915
    • Castle.core 3.3.1
    • EntityFramework 6.1.1

Next, in the "Easymemo.repositories" project, create a new class named Easymemocontext, which inherits from the System.Data.Entity.DbContext class, with the following code:

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 use of the standard entity Framework Code first, but Apworks's best practice suggests that the Dbset attribute is defined only for the aggregate root, which makes the dbcontext definition very concise and intuitive.

The next step is to define some type/database mappings for the entities in the domain model. Based on the standard Entity Framework usage, we can define a series of subclasses that inherit from the Entitytypeconfiguration generic class, define the mapping rules in these subclasses, The instances of these subclasses are added to the Configurations collection in the Easymemocontext onmodelcreating overloaded method, or the mapping rules can be defined directly in the Onmodelcreating method. I still prefer the previous approach, which is to create a subclass that inherits from Entitytypeconfiguration for each entity that needs to configure the mapping, although it looks like there will be a lot of extra class definitions, but doing so will make the code structure more readable. For example, for the account object, we can define the mapping 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 (+);        Property (x = X.email)            . IsRequired ()            . Isunicode ()            . Hasmaxlength (+);        Property (x = x.isdeleted). Isoptional ();        Property (x = X.name). IsRequired ()            . Isunicode ()            . Hasmaxlength (+);        Property (x = X.password). IsRequired ()            . Isunicode ()            . Hasmaxlength (4096);    }}

Then add an instance of the class to the onmodelcreating overloaded method:

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {    modelBuilder.Configurations.Add (new Accountentityconfiguration ());}

OK, next use a similar method to define the mapping configuration classes for the required entity types in the domain model, and then add the instances of those classes to the onmodelcreating overloaded method in turn. Limited to space, the code is not listed here, you can at the end of this section click the Download code link, the source code to download to the local for reference.

Setting the database initialization policy

The Entity framework itself supports the following types of database initialization policies:

    1. Migratedatabasetolatestversion: Use the Code First database migration policy to update the database to the latest version
    2. Nulldatabaseinitializer: A database initializer with nothing to do
    3. Createdatabaseifnotexists: As the name implies, create a new database if the database does not exist
    4. Dropcreatedatabasealways: Always rebuild the database regardless of whether the database exists
    5. Dropcreatedatabaseifmodelchanges: Rebuilding a database only if the domain model changes

In practical applications, we can directly use the above database initialization policy, the Entity framework initializes the database based on the selected initialization policy and the mapping configuration information above, when invoking the Initialize method of the DB object. For demonstration purposes, we want to be able to prepare some data for us at the same time as the database is initialized, so that we can introduce the future content, so we could customize a set of database initialization policies where we write the required data to the database.

First, in the "Easymemo.repositories" project, create a new class named Databaseinitializestrategy and make it inherit the Dropcreatedatabaseifmodelchanges type:

public class Databaseinitializestrategy     : dropcreatedatabaseifmodelchanges<easymemocontext>{}

Then, overload the seed method in the type, adding 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 performing system administration Tasks",            Permissions = new list& Lt permission> {adminpermission}        };        var administrator = new account        {            DateCreated = datetime.utcnow,            DisplayName = "admin",            Email = "[ Email protected] ",            Name =" admin ",            Password =" admin ",            Roles = new List<role> {administrators}        };        Context. Accounts.add (administrator);        Base. Seed (context);}    }

So, we have our own database initialization policy, the next step is to use this strategy in the Easymemo system.

Run our Code

Open the "Easymemo.services" project and add a reference to the "Apworks.Repositories.EntityFramework" package by using the Manage NuGet packages feature in the same way as above. Then, under the Appp_start directory, create a new 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 the Application_Start method to the Databaseconfig.initialize:

public class webapiapplication:system.web.httpapplication{    protected void Application_Start ()    {        Globalconfiguration.configure (webapiconfig.register);        Databaseconfig.initialize ();    }}

Open the Web. config file for the Easymemo.services project, locate the EntityFramework node in it, and configure the node so that the Entity Framework can use the SQL Server database that 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 the "Easymemo.services" project as the startup project, then press F5, wait a moment, and when the browser appears, we can find the database that was automatically generated by the Entity Framework in SQL Server:

Open Microsoft SQL Server Management Studio, connect to the configured DB instance, and we can see that Easymemodb already appears in the database list:

And you can find our pre-prepared data:

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

Of course, we don't need to focus too much on this data model at the moment, after all, we're not going to database-oriented programming.

Start using the Entity Framework-based Apworks warehousing service

Before using the Apworks warehousing service, we first need to configure the entire operating environment of the Apworks. Based on the discussion of the previous hierarchical structure, the Easymemo.services project is a RESTful API project on the server side, implemented by ASP. NET WEB API 2.0. Therefore, the configuration for the Apworks Framework runtime environment will also occur in this project. To enable the Web API controller to get an example of apworks warehousing and its context, we adopted IOC technology and selected Microsoft unity as a dependency injection framework, which is the only dependency injection framework currently supported by the Apworks framework. Of course, Apworks's dependency injection system is extensible, and you can scale it to your project needs, enabling it to support multiple mainstream dependency injection frameworks.

Configuring the operating environment for Apworks

First, add the following package references to the Easymemo.services project through manage NuGet packages:

    1. Apworks.ObjectContainers.Unity:Apworks Support library for Unity
    2. Unity.WebAPI:Unity support for the ASP. NET Web API, which enables ASP to use unity as a dependency injection framework

Next, as in the previous add Databaseconfig class, under the "App_start" folder of the "Easymemo.services" project, create a new static class named Apworksconfig, with the following contents:

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<unityco                Ntainer> (); Unitycontainer.registerinstance (New Easymemocontext (), New Perresolvelifetimemanager ()). Registertype<irepositorycontext, entityframeworkrepositorycontext> (New Hierarchicallifetimem                    Anager (), New Injectionconstructor (New Resolvedparameter<easymemocontext> ())) . Registertype (typeof (Irepository<>), typeof (ENTITYFRAMEWORKREPOSITORY&Lt;>));            GlobalConfiguration.Configuration.DependencyResolver = new Unitydependencyresolver (UnityContainer); })            .    Start (); }}

Note: This is the way to configure the fluent Interface (fluent interface). Apworks also supports Web.config/app.config-based configuration, and I'll introduce you to this section in the future.

Then, again, 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,apworks's operating environment configuration is basically done. Next, let's create a simple restful API to run through the process.

Start our ASP. NET Web API Tour

In the "Easymemo.services" project, locate the "Controllers" directory, right-click and select "Add –> Controller" in the context menu. In the Add Scaffolding dialog box that pops up, select Web API 2 controller-NULL:

In the "Controller name" column of the Add Controller dialog box that pops up, fill in "Accountscontroller":

When you click the Add button, Visual Studio opens the Accountscontroller code-editing interface. At this point, we 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.ac        Countrepository = accountrepository;    This.unitofwork = Unitofwork; } [HttpGet] [Route ("Name/{name}")] public ihttpactionresult getbyname (string name) {var account = this . Accountrepository.find (SPECIFICATION&LT;ACCOUNT&GT;. 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 simple? Let's start the "Easymemo.services" Project again: Set the project as the startup project, then press F5 directly on the same "403.14–forbidden" page as above and enter it in the browser:

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

At this point, you can see the result returned by this restful API: it returns the details of the admin account:

Summarize

This article details how to use the Entity Framework in the Apworks framework and provide an infrastructure for warehousing and its context for restful services of an ASP. Starting with the next step, we'll focus on all aspects of the ASP implementation, including exception handling, authentication and authorization, data transfer objects and view models, and more.

Source code Download

Please "click here" to download the Easymemo solution source code as of this article.

Apworks Framework Combat (VI): Using the Entity Framework-based warehousing infrastructure

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.