Entity Framework4.0 (i) overview (EF4 's database First method)

Source: Internet
Author: User
Tags response code scalar

Transferred from: http://www.cnblogs.com/marksun/archive/2011/12/15/2289582.html

Entity Framework4.0 (hereafter referred to as: EF4) is a Microsoft ORM (object-relation-mapping) framework. As with other ORM (e.g., nhibernate,hibernate), one is to enable the developer to manipulate the relational data table in the manner in which the object is manipulated. Second, in order to shield the database of the different vendors, the developers write Crud (Create,retrieve,update,delete) operations for the ORM Framework, and the ORM framework translates these operations into dialects of different database vendors.

EF4 has changed a lot compared to the previous version:

    • POCO (Plain old CLR Objects) Support: You can persist, track, state management, and so on for business objects that contain business logic.
    • Model-Driven Development: EF4 provides three scenarios: (1) First establish a database and a data table, generated by the database table business model. (2) First design the business model with the designer and generate the data table from the business model. (3) The way of pure code, not the designer, but the implementation of the interface and class, in order to map with the database. The model driver here refers to the scheme (2).
    • Deferred loading of associated objects: In previous versions, it was not supported to automatically load the associated object via the navigation properties, to use include (), or to display load (). In EF4, it is supported to automatically load the associated object through the navigation properties.
    • A functional call to a database stored procedure and a custom function: stored procedures and custom functions in the database can be mapped to ObjectContext object methods, which are called directly in the program.
    • The template and build process for customizing code generation: EF4 and T4 use templates that control the generation of code. EF4 is used in conjunction with WF (Windows work Flow) to control the process of generating code.
    • By default: The entity set takes the plural and the entity is named by the singular: the entity set in the previous version is the same as the entity's name, which makes people feel confused. Now the EF4 solves the bug.
    • Complex properties: If a property has only one item, we call the property a scalar attribute (scalar property). If a property is composed of multiple scalar attributes, we say that the attribute after the combination is a complex property. If there is a complex attribute in an entity. When mapped to a data table, each scalar property inside the complex property is mapped to a separate field.

In the overview section, I'll use three blog posts to demonstrate a simple way to create an app using EF4. In order to first show you a EF4 of the overall image, to avoid too much attention to detail, but not clear the whole picture. I've seen a lot of EF4 blogs in the blog Park, and they're all very well-spoken. But I think it is a bit too deep, and the knowledge point over a bit steep: not conducive to EF4 novice understanding and learning. There is no EF4 of the relevant books for everyone to learn the detailed reference. So, I'll try to write some useful, simple, transitional posts for everyone. Avoid obscure technical terminology, get you started quickly, and then delve into it in your specific use.

EF4 supports three methods of building: 1. Database first method. 2.Model first method. 3.Code first method. Developers can choose either method based on the specific project situation. To try to keep the detailed steps of each method in order, the first three posts are not explained in depth. I will gradually expand and deepen the internal mechanism and knowledge of EF4 in subsequent chapters.

Well, not much to say. Down to the bottom. This time we will briefly demonstrate the following:1. Database first method.

=========================================================================

Let's create a small example of a simple Windows Form: Take the Northwind database as an example.

First, create the Efdemo windform application. Such as:

Right-click on the Efdemo project to select Add->new item. Select the ADO Entity Data Model. In the Name box, type: Northwind, click Add.

Select "Generate From Database" to click Next. Such as:

Select the database server, and the data table. Everyone should be no stranger to this. A connection string (used to connect to the database) is generated and saved in the configuration file. Such as:

The tables, we choose categories, products two tables. TICK: Pluralize or Singularize generated object names and Include foreign key columns in model.

Namespace you can set it yourself, we use the default value here. Click Finish. For example:

The EF4 generated entity graph, as follows:

The design WinForm form is as follows:

After running, when you click on the: Initlistbox button, fill the Lboxcategory, and when selected in Lboxcategory, all products under that category will be displayed in Lboxproduct. Such as:

In the following two event handling code: If either method one is used or method two is used. I recommend using method two for both methods because it is more efficient. Here is a way to demonstrate the use of the next join (join).

The click Code in Initlixtbox is as follows:

//method One: We use loops to iterate through the collection elements of the query results and then add them to the control. //this.lboxCategory.Items.Clear ();//using (northwindentities context = new NorthwindEntities ())//{//var categories = from category in context. Categories//Select New {category. Categoryid,category. CategoryName};//foreach (var c in categories)//    {//This.lboxCategory.Items.Add (c.categoryname);//    }//}//method Two: This method is the way to specify the data source. No need to use This.lboxCategory.Items.Clear ();//to clean up the results of the last show. When you specify the data source again, the control displays the most current data information.             using(NorthwindEntities context =Newnorthwindentities ()) {                varCategories = fromCategoryinchcontext. CategoriesSelect New{category. CategoryID, category.                CategoryName}; //Note: When assigning a data source to a control, the assignment statements for DataSource are assigned after DisplayMember and ValueMember .//Otherwise, the assignment of DisplayMember and ValueMember does not take effect.                  This. Lboxcategory.displaymember ="CategoryName";  This. Lboxcategory.valuemember ="CategoryID";  This. Lboxcategory.datasource =categories; }

The Lbcategory Select Index Change event response code is as follows:

//method One: We use loops to iterate through the collection elements of the query results and then add them to the control. //this.lboxProduct.Items.Clear ();//if (This.lboxCategory.SelectedItem! = null)//{//string CategoryName = This.lboxCategory.SelectedItem.ToString ();//this time the direct use of CategoryName as a filter condition requires the use of joins, because the product contains only CategoryID, not CategoryName. //using (northwindentities context = new NorthwindEntities ())//    {//var products = from product in context. Products//join category in context. Categories on product. CategoryID equals category. CategoryID//The where category. CategoryName = = CategoryName//Select New {product. ProductName};//foreach (Var p in products)//        {//This.lboxProduct.Items.Add (p.productname);//        }//    }//}//method Two: This method is the way to specify the data source. No need to use This.lboxProduct.Items.Clear ();            if( This. lboxcategory.selectedvalue! =NULL)            {                //get the category ID number                intCategoryID = Convert.ToInt32 ( This. lboxCategory.SelectedValue.ToString ()); //this time, using CategoryID as a filter, no connection (join) is required, because the product contains CategoryID.                 using(NorthwindEntities context =Newnorthwindentities ()) {                    varProducts = fromProductinchcontext. ProductswhereProduct. CategoryID = =CategoryIDSelect New{product.                    ProductName}; //Note: When assigning a data source to a control, the assignment statements for DataSource are assigned to DisplayMember and ValueMember after the assignment of the value.//Otherwise, the assignment of DisplayMember and ValueMember does not take effect.                      This. Lboxproduct.displaymember ="ProductName";  This. Lboxproduct.datasource =Products ; }            }

Entity Framework4.0 (i) overview (EF4 's database first method)

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.