The formation of Entity Framework object Framework -- separation and combination of the data transmission model DTO and Entity model Entity, dtoentity
When using the Entity Framework, most of the time we operate on Entity model Entity, which is combined with the database operation context and can be implemented using various convenient methods such as LINQ, everything looks wonderful. However, if you consider using WCF, you may encounter many related traps or errors. Because the object of the Entity model Entity may include references of other entities, it cannot be serialized in WCF and an error occurs. In addition, when using WCF, Express expressions may not be effectively used, the inability to directly use LINQ and other problems all come together. Based on the above problems, this article describes the solution to my entire Entity Framework, and introduces the data transmission model DTO to solve the problem, this article mainly introduces the separation and combination of the data transmission model DTO and Entity model Entity, so as to implement a smooth and efficient WCF application framework.
1. Entity model Entity cannot be serialized in WCF
For example, the Entity Framework Entity class we define contains references to other objects. For example, if a Role object is associated with other tables, the traditional method is used by default, add the [DataContract] Method to the object class.
/// <summary>
/// Roles
/// </ summary>
[DataContract (IsReference = true)]
public class Role
{
/// <summary>
/// The default constructor (requires the initialization of properties here)
/// </ summary>
public Role ()
{
this.ID = System.Guid.NewGuid (). ToString ();
// Children = new HashSet <Role> ();
// Users = new HashSet <User> ();
}
#region Property Members
[DataMember]
public virtual string ID {get; set;}
/// <summary>
/// Role Name
/// </ summary>
[DataMember]
public virtual string Name {get; set;}
/// <summary>
/// parent ID
/// </ summary>
[DataMember]
public virtual string ParentID {get; set;}
[DataMember]
public virtual ICollection <Role> Children {get; set;}
[DataMember]
public virtual Role Parent {get; set;}
[DataMember]
public virtual ICollection <User> Users {get; set;}
#endregion
}
Use the following code in the WCF Service Interface.
public class Service1 : IService1
{
public List<Role> GetAllRoles()
{
return IFactory.Instance<IRoleBLL>().GetAll().ToList();
}
.........
When we use it in WCF, we will receive the following prompt.
An error occurred while receiving the http Response to HTTP: // localhost: 11229/Service1.svc. This may be caused by binding the service endpoint without using the HTTP protocol. This may also be caused by the server suspending the HTTP request context (possibly because the service is disabled. For more information, see server logs.
By default, to support some of its advanced features (such as delayed loading), Entity Framework sets the automatically generated proxy class to true by default. If we need to disable automatic generation of proxy classes, we can perform processing settings in the database operation context DbContext.
Configuration.ProxyCreationEnabled = false;
If it is set to false, the WCF Service can work normally, but other object sets in the object class objects are empty, that is, the reference content cannot be returned by WCF.
At the same time, in the Entity Framework, this kind of Entity class runs through each layer, which is not recommended because the data transmitted in WCF is all data with serial numbers, it also cannot be used locally to process data.
So how should we build the Entity Framework based on the reference of WCF?
2. Introduction of Data Transmission object DTO
We have introduced the disadvantages of directly using Entity Framework object class objects. If this Entity class is used all the way, many object references in it are empty, we are inconvenient to use on the interface layer, and may also cause many issues related to the WCF framework.
Based on the above problem, we introduced a DTO (data transmission object) thing.
A Data Transmission object (DTO) is a non-behavior POCO object. It aims to encapsulate the data of a domain object and implement data transmission between layers, the interface presentation layer interacts with the application layer through data transmission objects (DTO. The data transmission object DTO is not a business object, and the data transmission object is designed according to the UI requirements.
This object is independent from the object class of the specific data storage. It can be called a ing body of the object class. The name can be different from the object class, and the number of attributes can also be different from the object class. Since another DTO Object layer is introduced outside the Object layer, mutual conversion is inevitable. To avoid manual ing, we introduced another powerful automated ing tool, AutoMapper, to help us quickly, efficiently, and intelligently implement the ing processing of two-layer objects.
The use of AutoMapper is relatively simple. Generally, if the object property remains unchanged, they will implement automatic property ing, as shown below.
Mapper.CreateMap<RoleInfo, Role>();
If the attribute names of the two are different, you can use the ForMember method to specify them, as shown in the following code.
AutoMapper.Mapper.CreateMap<BlogEntry, BlogPostDto>() .ForMember(dto => dto.PostId, opt => opt.MapFrom(entity => entity.ID));
AutoMapper can also write the ing information to a class and then load it in a unified manner.
Mapper.Initialize(cfg => { cfg.AddProfile<OrganizationProfile>();});
So based on the preceding illustration, because we use the DTO and Entity automatically generated by the code generation tool, their attribute names are consistent, then we only need to map the two objects at the application layer.
public class RoleService: BaseLocalService <RoleInfo, Role>, IRoleService
{
private IRoleBLL bll = null;
public RoleService (): base (IFactory.Instance <IRoleBLL> ())
{
bll = baseBLL as IRoleBLL;
// DTO and Entity model mutual mapping
Mapper.CreateMap <RoleInfo, Role> ();
Mapper.CreateMap <Role, RoleInfo> ();
}
}
Based on the ing relationship of the internal connection, we can provide unified DTO object services at the Facade interface layer, and the business logic layer (that is, the Entity Framework is processed) it still uses its Entity object for transmission. Below I will provide several encapsulated basic class interfaces for you to understand the connection between DTO and Entity.
1) input the DTO object, convert it to the Entity object, and insert it using the EF object.
/// <summary>
/// insert the specified object into the database
/// </ summary>
/// <param name = "dto"> specified object </ param>
/// <returns> Successful execution returns <c> true </ c>, otherwise <c> false </ c> </ returns>
public virtual bool Insert (DTO dto)
{
Entity t = dto.MapTo <Entity> ();
return baseBLL.Insert (t);
}
2) obtain the Entity object from the EF framework based on the conditions, and return the DTO object after conversion.
/// <summary>
/// Query the database and return the object with the specified ID
/// </ summary>
/// <param name = "id"> ID primary key value </ param>
/// <returns> If specified, return the specified object, otherwise return Null </ returns>
public virtual DTO FindByID (object id)
{
Entity t = baseBLL.FindByID (id);
return t.MapTo <DTO> ();
}
3) obtain the Entity set object from the EF framework based on the condition and convert it to a DTO list object.
/// <summary>
/// return all objects in the database
/// </ summary>
/// <returns> </ returns>
public virtual ICollection <DTO> GetAll ()
{
ICollection <Entity> tList = baseBLL.GetAll ();
return tList.MapToList <Entity, DTO> ();
}
3. Entity Framework Structure
For the purpose of convenient management, each module can adopt a fixed and hierarchical method to organize the business content of the module. Each module is implemented in a small and dirty way. The project structure of the entire business logic layer of the Instance module is as follows.
If you want to use WCF, the overall structure is similar to that of my previous hybrid framework, and the responsibilities of each module are basically unchanged. However, the Implementation layers separated by the DAL layer are the same, the change is the Mapping layer of each database, and the DTO model is added. The specific project structure is as follows.
The project description is as follows:
EFRelationship |
The business modules and interfaces of the system, database access modules and interfaces, DTO objects, object objects, and various database ing classes. This module is closely integrated with the code generated by the powerful code generation tool Database2Sharp, highly abstract inheritance at each layer, and supports multiple databases using generics. |
EFRelationship. WCFLibrary |
The business logic module of the system's WCF Service. This module puts the business management logic together by referencing files to facilitate the deployment and call of the WCF Service. |
EFRelationshipService |
The Framework's WCF Service module, including the basic service module BaseWcf and business service module, manages and releases separately for convenience. |
EFRelationship. Caller |
Defines the Fa C ade application interface layer implemented by a specific business module, and packages Winform call methods and WCF call methods. |
Take the design of a membership system as an example. The Assembly relationship is as follows.
Let's take a look at the design results of the entire architecture as follows.
Among them, the business logic layer module (and other application layers) provides many entity-based public class libraries (WHC. framework. EF), where the inheritance relationship is enlarged to understand the inheritance relationship details, the effect is as follows.
I have provided a good overview of my EF Entity Framework Design ideas. These layers are finally integrated generation using the code generation tool Database2Sharp to improve the purpose of rapid production, all naming rules are unified. Next I will have the opportunity to write another article to introduce the logic of code generation.
The two factory classes highlighted on the left, one ifacloud is based on the local direct connection mode, that is, directly using the EF framework object for processing; the other CallerFactory is an interface implemented based on the Facade layer, point to the WCF data service object according to the configuration, or directly connect to the object for data operation.
This series of articles is as follows:
Entity Framework formation journey -- Entity Framework based on generic warehousing model (1)
Entity Framework formation tour-using Unity object dependency injection to optimize Entity Framework (2)
The formation of Entity Framework object Framework -- Implementation of unified and asynchronous operations of basic interfaces (3)
Entity Framework formation journey-processing of Entity Data Model (EDM) (4)
Entity Framework object Framework formation journey -- Code First Framework Design (5)
Entity Framework object Framework formation journey -- using Fluent API configuration in Code First mode (6)
The formation of Entity Framework -- separation and combination of data transmission model DTO and Entity model Entity