Entity Framework object Framework formation journey-Entity Framework based on generic warehousing model (1), entityframework

Source: Internet
Author: User

Entity Framework object Framework formation journey-Entity Framework based on generic warehousing model (1), entityframework

I haven't written a blog for a long time, and some readers often ask some questions. However, I have been very busy recently. Besides my daily work, it usually takes time to continue studying Microsoft's EntityFramework. This entity framework has added many features (such as LINQ), and is now mature in applications. The reason why it has not been compiled into an entity framework that conforms to its own development model is that, this is because the framework is quite different from my original EnterpriseLibrary-based model. However, the Entity Framework has been launched for a long time and has now gone to EntityFramework6. I heard that 7 is coming soon.

As I read a lot of project source code and learned deeply about various technical points of the Entity Framework, I have some opinions and experiences on many of these aspects. I hope that through this series, able to analyze with readers step by step, step by step to learn the most popular Microsoft at present.. NET development framework. This article describes The Entity Framework of Generic Repository Pattern step by step from The basics.

1. Initial impressions of the Entity Framework

You can add an [ADO. NET Object Data Model] item in Winform or Web project to create an SqlServer-based object framework project step by step. At first, we can use it without considering any design patterns. Therefore, we may create a simple project code, which helps us understand some basic working principles of the Entity Framework.

Select the data connection and one or two tables for testing for this project, and then complete the creation. NET Object Data Model] After creation, we can see that a Model1.edmx file is added to the project, and several project files are generated at the same time, this includes the data access object SqlserverContext and several object classes (the table name by default). You can also open the edmx file to modify the object class attributes, as shown below.

After the data is generated by default, we can use this data access context object SqlserverContext to perform related data processing operations. The simple test code is as follows.

Private void GetIntData () {// create a data access object var context = new SqlserverContext (); // create an object class and assign the value TB_Province info = new TB_Province (); info. ID = 100001; info. provinceName = "test Province"; context. TB_Province.Add (info); context. saveChanges (); // judge whether the record contains TB_Province info2 = context based on the primary key. TB_Province.Find (info. ID); if (info2! = Null) {Console. WriteLine ("the record already exists! "); // If an object exists, delete the context first. TB_Province.Remove (info2); context. saveChanges (); // check whether the object info2 = context is deleted. TB_Province.Find (info. ID); if (info2 = null) {Console. writeLine ("record deleted! ") ;}} // Obtain and bind all records to the list. Var list = context. TB_Province.ToList (); this. dataGridView1.DataSource = list ;}

The final interface result is that records can be displayed to the list after various operations are successfully executed.

2. Working Principle of the Entity Framework

1) Introduction to data access context objects

From the code above, we can see that the data access context object SqlserverContext can interact directly with the database, and the table object can be added, deleted, modified, and queried, so how is this class? Why is this feature available?

Let's take a look at its code. The class code of SqlserverContext is as follows (the code is automatically generated ).

    public partial class SqlserverContext : DbContext    {        public SqlserverContext()            : base("name=SqlserverContext")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }            public virtual DbSet<TB_City> TB_City { get; set; }        public virtual DbSet<TB_Province> TB_Province { get; set; }        public virtual DbSet<TB_DictType> TB_DictType { get; set; }    }

The Code DbSet <TB_Province> TB_Province represents a specific data access object, which accesses the data of table TB_Province. Others are similar. We can see that the built-in object DbSet of. NET already supports some common operations.

The EMDX file is an XML file, and its content is as follows.

The Entity Framework uses XML ing (ORM) to encapsulate the interaction process from the database to the entity class and from the entity class to the database, for specific procedures, refer to the following introduction to the Entity Data Model (EDM.

 

2) Introduction to the Entity Data Model (EDM)

The main point of the Entity Framework is the Entity Data Model (EDM), a conceptual model used to describe application domain objects. The Entity Framework allows developers to query object data models without having to worry about specific database operations. The Entity Data Model and the relationship between entities are defined in XML format, and the developer manages strongly typed classes based on the entity of the model.

The database-specific ADO. NET provider, the Entity Framework converts a query created for the Entity data model to a storage query (such as a T-SQL) and then sends it to the database. Entity Framework converts query results to objects defined by strongly typed object classes.

The Entity Data Model (EDM) is composed of three concepts. The conceptual model is defined by the conceptual architecture language file (. csdl), The ing is defined by the ing standard language file (. the storage model (also known as the logical model) is defined by the storage architecture language file (. ssdl. The three are combined in the EDM mode. The EDM mode in a project is represented by a file with the extension. edmx. This file containing EDM can be designed using the EDM designer in Visual Studio. Because this file is essentially an xml file, you can manually edit this file to define the CSDL, MSL, and SSDL parts.

CSDL defines the concept model of EDM or the soul of the entire program. This document defines the concept of a model from the perspective of a program language. That is, the defined entities, primary keys, attributes, and associations all correspond to the types in. NET Framework.

The SSDL file describes the concepts in tables, columns, relationships, primary keys, indexes, and other databases.

The MSL file corresponds to the CSDL and SSDL described above, mainly including the correspondence between attributes in CSDL and columns in SSDL.

 

Through the ing relationships between the above three XML files, in the program, the entity class of strong data is mainly used for processing, and any processing and modification of the object class, the database execution statement is obtained after parsing, and then submitted for processing.

 

3. Generic warehousing model Entity Framework

Although it is fast to build a framework based on the first point, such an approach is definitely not available in medium and large projects, because the generated code still needs to be modified and adjusted in multiple steps, and the purpose of reuse is not very good. In many cases, manual coding is required, and the structure is not very clear, therefore, we need to optimize and refine the framework step by step.

Before introducing The Generic warehousing model Entity Framework (The Entity Framework of Generic Repository Pattern), let's review The layered structure of my previous Winform development Framework, this framework is based on the Enterprise Library. Common layered modes include the UI Layer, BLL layer, DAL layer, IDAL layer, Entity layer, and public class Library layer.

After the database is designed, you can use the code generation tool to obtain information and relationships of table objects and quickly generate Corresponding Hierarchical code, in this way, the architecture, hierarchy, naming rules, and other aspects can be consistent and can be developed quickly.

In addition, this layered mode is also a common layered structure. Can the Entity Framework we want to introduce be constructed in this way? Can I develop the overall framework based on the template generated by the code generation tool?

The following describes the implementation process of the generic warehousing model framework.

1) the code for the object class is as follows (first generated by table name ).

    public partial class TB_City    {        public long ID { get; set; }        public string CityName { get; set; }        public string ZipCode { get; set; }        public Nullable<long> ProvinceID { get; set; }    }

2) Data Access Base Class interface layer (several test base class interfaces are defined)

/// <Summary> /// data access layer base class interface /// </summary> /// <typeparam name = "T"> Object Type </typeparam> public interface IBaseDAL <T> where T: class {T Get (object id); IList <T> GetAll (Expression <Func <T, bool> whereCondition); IList <T> GetAll ();}

3) data access layer base class Implementation Layer

/// <Summary> // data access layer base class Implementation Layer /// </summary> /// <typeparam name = "T"> Object Type </typeparam> public abstract class BaseDAL <T>: IBaseDAL <T> where T: class {protected DbContext baseContext; protected IDbSet <T> objectSet; public BaseDAL (DbContext context) {this. baseContext = context; this. objectSet = this. baseContext. set <T> ();} public T Get (object id) {return objectSet. find (id);} public IList <T> GetAll () {return objectSet. toList <T> ();} public IList <T> GetAll (Expression <Func <T, bool> whereCondition) {return objectSet. where (whereCondition ). toList <T> ();}}

4) specific data access object interface definition (city table as an example)

/// <Summary> /// City Data access layer interface /// </summary> public interface ICityDAL: IBaseDAL <City> {}

5) Specific Data Access Object Implementation Layer (city table as an example)

/// <Summary> // City Data Access Object /// </summary> public class CityDAL: BaseDAL <TB_City> {protected MyDataContext context; /// <summary> /// constructor /// </summary> /// <param name = "context"> </param> public CityDAL (MyDataContext context ): base (context) {this. context = context ;}

6) Data Warehousing objects (context objects)

    public class MyDataContext : DbContext    {        public MyDataContext() : base("name=sqlserver")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }            public virtual DbSet<TB_City> City { get; set; }    }

The layers of BLL and IBLL are similar to those of the data access layer, which mainly improves the implementation of business integration.

The layered structure of the final implementation of the warehousing model framework is as follows.

The above is the beginning of my preliminary exploration of the Entity Framework based on the generic warehousing model. I will continue to analyze the problems in this series, we will continue to optimize and improve this Entity Framework based on the generic warehousing model. I hope you will like it and continue to support it.

Please pay attention to my blog for indexing this series of articles and sort them out and release them now!

This article is organized and published by anthropomorphic www.zaojuzi.com.


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.