Thursday, December 29, 2011

Start using .Net Entity Framework - 2

After having created the Windows Forms Application project and generated the data model from the database let's see how we can access the database through the model, using a small illustrative example.

In the Form1 form, created automatically when creating the Windows Forms Application project, we will create a comboBox, dragging it from the toolbox.


In the Properties tab we change its name to paisesBox1.


Then we add an event handler for the Load event of Form1 form (last line of code in the InitializeComponent () method below):


And create the method corresponding to the event handler (Form1_Load ()):


This method will fill the paisesBox1 comboBox when the form Form1 starts.
Let's see how this is done in more detail:

   - Line            simpleEntityFrameworkApp.bdExemploEntities dbContext;

     declares variable dbContext of type bdExemploEntities, which corresponds to the created data model.

   - Line
            dbContext = new simpleEntityFrameworkApp.bdExemploEntities();

     creates the object with the data model, responsible for the mapping to the database, and assigns it to the variable dbContext.

   - Line
            paisesBox1.DataSource = dbContext.Paises;

     assigns Paises, in the database context created before, to the DataSource property of the comboBox, indicating that this is from where data for the comboBox should be read.

   - Lines
            paisesBox1.DisplayMember = "nome";
            paisesBox1.ValueMember = "idPais";


     identify attributes of Pais (one country; whether Paises are several countries) that shall be displayed in the comboBox (property DisplayMember) and yelded as selectedValue property of the comboBox when a country (país) is selected (ValueMember).

This code excerpt reads all lines of table Pais and fills the comboBox.

If, for example, we intended to filter the data by some criteria we could use LiNQ to do it, before we associate the result to the comboBox.

For instance, line
            paisesBox1.DataSource = dbContext.Paises;

could be replaced by:

          List<Pais> listaPaises;
          IQueryable<Pais> paisesQuery = from p in dbContext.Paises
                                         where p.idPais > 20
                                         select p;
          listaPaises = paisesQuery.ToList<Pais>();
          paisesBox1.DataSource = listaPaises;

In this case, the comboBox would be filled only with the countries (países) with ID (idPais) higher than 20.

In a forthcoming article we will see how to update the database using the model created with the Entity Framework.

If anyone is interested in the C# code used in this example, please ask for it in a comment to this blog entry.


Other related articles:
    - ADO.Net Entity Framework
    - Start using .Net Entity Framework - 1





No comments:

Post a Comment