Data Binding of entity framework4.0 (8) EF4

Source: Internet
Author: User

We have introduced how to add, delete, modify, and query EF4 data. With the help of EF4, the workload of developers will become very simple.

This time, we will introduce the data binding function of EF4. This time, you will find another simple use of EF4: EF4 as the "Data Source" of the data source control ".

Khan !! This is a good choice. Why?

Because when we use a data source control in a project, we need to point out where to get data from the data source control, that isData source of the data source control. In the past, dataset was used as the data source control. Then, the dataadapter interacts with the database and fills the data in the dataset. Then it is displayed on the display control (such as the datagridview ). This time, EF4 is used to replace the tasks previously completed by dataadapter and dataset. We already know That EF4 can map records of data tables into entity and entity sets and track and manage these entities. Then we can use these entities and entities as the data source control. In this way, the data source control does not need to deal with the database directly, but interacts with the EF4 entity container (container), and then the EF4 interacts with the database.

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

Now, start vs2010.

1. File-> New --> Windows form project. (Name: efdatabindingdemo)

2. On the solution, right-click --> Add --> new project --> class library. (Name: efdata ). (In order to reflect the idea of layering, this time the *. edmx file is created separately in a class library project .),

3. Right-click the efdata class library project and choose --> Add --> ADO. NET Entity Data Model. (Name: northwind ). Click "OK", for example:

4. Find the northwind database on the server. For example:

5. Select three tables: category, product, and supplier. For example:

6. Add a project reference to the efdatabindingdemo project: (for example, do not forget to bake the app. config file in the efdata project to the efdatabindingdemo project. The easiest way is to drag the file to the efdatabindingdemo project with your mouse)

7. Add. Net class library reference, such:

8. Select the efdatabindingdemo project and open the data source window, for example:

9. Click the left button in the data source window to add a data source, such as the current data source type, for example:

10. Click Next. For example, if there is blank, your *. edmx has forgotten the compilation,

Select "cancel ". Compile the efdata project and add the data source again.

Note:: When you select the "efdata" project with the mouse, the data source window displays the data source of the "efdata" project. When you select the efdatabindingdemo project, the data source window displays the data source of the efdatabindingdemo project. Do not confuse.

11. Re-select the efdatabindingdemo project and add a data source in the data source window -->. Repeat Step 9, for example:

12. The data source window displays the added data source, for example:

13. Drag the "product" data source node to form1 and release the mouse. For example: (observe the five labels in the figure. This is automatically added)

 

14. Run the program, for example:

Note: I was disappointed that I didn't get the data? We used to pointDatasetWhen you bind a control to a data source, the data is automatically retrieved from the database and can be loaded to the data. But now we are not directly using the database, but using EF4 (actually using the EF4 container), and then dealing with the database with EF4. Because all our entities are placed in the Context container, but we have not created this container, so we cannot load the data (entity ).

15. Add the following code to the load event of the form:

1 private void form1_load (Object sender, eventargs E)
2 {
3 var context = new northwindentities ();
4 objectresult <product> Products = context. Products. Execute (mergeoption. appendonly );
5 // assign values to the data source attributes of the data source control.
6 This. productbindingsource. datasource = products;
7}

 

Run the program, for example: (the data is loaded, but the data in the category and supplier columns only has the type, and there is no actual data value)

16. Right-click productdatagridview --> edit columns; add two columns: categoryname and suppliercontactnamename. For example, (the name of each column is the same as that of headertext) to move the newly added columns to the bottom for easy viewing.

Add the following code to the rowprepaint event of the productdatagridview control:

 1 private void productDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
2 {
3 if (e.RowIndex < productBindingSource.Count)
4 {
5 var prod = (Product)productBindingSource[e.RowIndex];
6
7 var grid = productDataGridView;
8 if (prod.Category != null)
9 {
10 grid.Rows[e.RowIndex].Cells[CategoryName.Index].Value = prod.Category.CategoryName;
11 }
12
13 if (prod.Supplier != null)
14 {
15 grid.Rows[e.RowIndex].Cells[SupplierContactName.Index].Value = prod.Supplier.CompanyName;
16 }
17 }
18 }

 

17. Run the Code: (the two red boxes in the figure are pre-processing columns and post-processing columns)

18. Use the add, delete, and save functions:

There is a small black solid triangle in the upper right corner of the productdatagridview control, called "Smart Tag ". Click on the Smart tag and set enable adding, enable editing, and enable deleting to the selected status.

The navigation bar at the top of the form has three icons: add, delete, and save. Right-click and select "enable. Select them as available. Add click events for the three icons respectively (double-click the icon above)

We move the context defined in the form load event to the class, so that this context variable can be used by multiple methods.

Add. The delete button directly modifies productbindingsource. Productbindingsource directly affects the changes of productdatagridview. We don't have to deal with this.

The following code processes the Save button event:

 1  private void productBindingNavigatorSaveItem_Click(object sender, EventArgs e)
2 {
3
4 try
5 {
6 this.productBindingSource.EndEdit();
7 context.SaveChanges();
8 MessageBox.Show("save successfuly");
9 }
10 catch (Exception ex)
11 {
12 if (ex.InnerException != null)
13 MessageBox.Show(ex.InnerException.Message.ToString());
14 else
15 MessageBox.Show(ex.Message.ToString());
16 }
17
18 }

Run the program. You can add, modify, and delete the program and save it to the database.

(Note:

1. An exception may occur when you delete the product because the foreign key in the order_detail table in the database references the primary key in the product. Therefore, you can only delete products that are not referenced by other tables.

2. generally, when the interface is displayed, we do not want to see the ID number, because these are meaningless to users, therefore, we recommend that you hide this ID column (whether it is a primary key column or a foreign key column) in your project. It is hidden, not deleted, because we need to use these idnumbers in the program for crud operations.

3. when processing the data of an updated cell. I am confused: When I used dataset for data binding, I could directly feedback changes to cells to the database. This time, when I used EF, however, you cannot change the cell to the database, even if context is called. savechanges () method. Later, I found a lot of information and failed to solve the problem. In an accidental test, I modified multiple cells at a time and saved them. This time it was saved successfully. The reason is that the number of modifications I made to cells is too small, and context does not update them into the database in time. Instead, it caches these modifications locally. But I just guessed it. I'm not sure. Hope someone else can give me some advice. Thank you .)

As you can see, we can easily process the data. Does it feel that the world is better. Haha.

The complete Form Background code is as follows:

Complete Form Background code

1 public partial class form1: Form
2 {
3 northwindentities context;
4
5 Public form1 ()
6 {
7 initializecomponent ();
8}
9
10 private void form1_load (Object sender, eventargs E)
11 {
12 context = new northwindentities ();
13 objectresult <product> Products = context. Products. Execute (mergeoption. overwritechanges );
14 // assign a value to the data source attribute of the data source control.
15 this. productbindingsource. datasource = products;
16
17}
18
19 private void productdatagridview_rowprepaint (Object sender, datagridviewrowprepainteventargs E)
20 {
21 if (E. rowindex <productbindingsource. Count)
22 {
23 var prod = (product) productbindingsource [E. rowindex];
24
25 var grid = productdatagridview;
26 if (prod. category! = NULL)
27 {
28 grid. Rows [E. rowindex]. cells [categoryname. Index]. value = prod. Category. categoryname;
29}
30
31 if (prod. Supplier! = NULL)
32 {
33 grid. Rows [E. rowindex]. cells [suppliercontactname. Index]. value = prod. Supplier. companyName;
34}
35}
36}
37
38
39
40 private void productbindingnavigatorsaveitem_click (Object sender, eventargs E)
41 {
42
43 try
44 {
45 this. productbindingsource. endedit ();
46 context. savechanges ();
47 MessageBox. Show ("Save successfuly ");
48}
49 catch (exception ex)
50 {
51 if (ex. innerexception! = NULL)
52 MessageBox. Show (ex. innerexception. Message. tostring ());
53 else
54 MessageBox. Show (ex. Message. tostring ());
55}
56
57}
58
59
60}

 

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.