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 data access object
            var context = new SqlserverContext ();
                    
            // Create a new entity class and assign 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 exists according to the primary key
            TB_Province info2 = context.TB_Province.Find (info.ID);
            if (info2! = null)
            {
                Console.WriteLine ("Record already exists!");

                // If there is an object, delete it first
                context.TB_Province.Remove (info2);
                context.SaveChanges ();

                // Check if the object is deleted
                info2 = context.TB_Province.Find (info.ID);
                if (info2 == null)
                {
                    Console.WriteLine ("Record deleted!");
                }
            }
            
            // Get all records and bind them to the list.
            var list = context.TB_Province.ToList ();
            this.dataGridView1.DataSource = list;
        }
The final interface effect is to be able to successfully perform various operations and display the records on the list.

2. The working principle of Entity Framework
1) Introduction to data access context objects

From the above code, we can see that the data access context object SqlserverContext can already directly interact with the database, and can realize the basic addition, deletion, and modification of the table object. So how is this class? Why have this function?

Let's look at its code first. The class code of SqlserverContext is shown below (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, the data access to the table TB_Province, the others are similar. We check that .NET's built-in object DbSet already supports some conventional operations.

The EMDX file itself is an XML file, and its contents are as follows.

The entity framework itself encapsulates the interaction process from the database to the entity class and the entity class to the database through XML mapping (ORM mode). For the specific process, we can refer to the following introduction to the entity data model (EDM).

 

2) Introduction to Entity Data Model (EDM)

Entity Framework The main point of the Entity Framework is the Entity Data Model (EDM), a conceptual model used to describe application domain objects. Entity Framework Entity Framework allows developers to make queries against the entity data model without having to worry about the specific operations of the database. The entities of the entity data model and the relationships between the entities are defined in the form of XML, and developers deal with strongly typed classes based on the entities of the model.

At runtime, using the database-specific ADO.NET provider, the Entity Framework converts queries created against the entity data model into stored queries (such as T-SQL) and sends them to the database. Entity Framework converts query results into objects defined by strongly typed entity classes.

The Entity Data Model (EDM) consists of three concepts. The conceptual model is defined by the conceptual architecture definition language file (.csdl), the mapping is defined by the mapping specification language file (.msl), and the storage model (also called logical model) is defined by the storage architecture definition language file (.ssdl). The combination of these three is the EDM model. The manifestation of EDM mode in the project is a file with the extension .edmx. This file containing EDM can be designed using the EDM designer in Visual Studio. Since this file is essentially an xml file, you can manually edit this file to customize the three parts of CSDL, MSL, and SSDL.

CSDL defines the EDM or the soul part of the entire program-the conceptual model. This file completely defines the concept of the model from the perspective of the programming language. That is, the entities, primary keys, attributes, associations, etc. defined therein correspond to the types in the .NET Framework.

The SSDL file describes the concepts that exist in databases such as tables, columns, relationships, primary keys, and indexes.

The MSL file is the correspondence between the CSDL and SSDL described above, and mainly includes the correspondence between the attributes in the CSDL and the columns in the SSDL.

 

Through the mapping relationship of the above three XML files, in the program, the entity class is mainly processed using strongly typed data, and any processing modification of the entity class will eventually be parsed to obtain the corresponding database execution statement, and then proceed Submitted and processed.

 

3. Entity framework based on generic storage mode
If the framework is built based on the first point, although it is very fast, this approach is definitely not desirable in large and medium-sized projects, because the generated code still needs to be modified and adjusted in multiple steps, and it is not well implemented for reuse. For purposes, many places require manual coding and processing, and the structure is not very clear, so the framework needs to be optimized and refined step by step.

Before introducing the Entity Framework of Generic Repository Pattern (Generic Repository Pattern), let ’s review my previous Winform development framework layered structure. This framework based on Enterprise Library, the common layered mode, can Divided into UI layer, BLL layer, DAL layer, IDAL layer, Entity layer, public library layer and so on.

This layering can be used to obtain the information and relationships of table objects through the code generation tool after the database design is completed, and the corresponding layered code can be quickly generated directly to achieve consistency in architecture, layering, naming rules, etc. And it is rapid development.

And this layered model is also a more general layered structure, so can the entity framework we are introducing also be constructed in this way? Is it possible to develop the overall framework in combination with the generation template of the code generation tool?

Now let's introduce the specific implementation process of the generic warehouse mode framework.

1) The code of the entity class is shown below (first generated according to the 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 (base class interfaces for several tests are defined)

    /// <summary>
    /// Data access layer base class interface
    /// </ summary>
    /// <typeparam name = "T"> Entity 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"> Entity 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 (for example, city table)

    /// <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 object (context object)

    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 layering of BLL and IBLL is similar to that of the data access layer. It is mainly to increase a copy to facilitate business integration and implementation, so I will not repeat them here.

The hierarchical structure of the warehousing mode framework is as follows.

The above is my preliminary exploration of the entity framework based on the generic storage model. The following will continue to analyze the problems in this series and continue to optimize and improve the entity framework based on the generic storage model. I hope you like it and continue to support it.

The index of this series of articles is as follows:

Entity Framework Entity Framework Formation Journey-Entity Framework Based on Generic Warehousing Mode (1)

Entity Framework Entity Framework Formation Journey--Using Unity Object Dependency Injection to Optimize Entity Framework (2)

Entity Framework Entity Framework Formation Journey-Unified and asynchronous operation of the base class interface (3)

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.