Entity Framework: Winforms Combobox Databinding is just weird...

I wanted to use Databinding on a Combobox in Winforms, like I did with Objects or a Dataset on Master-Detail relations.
Databinding with the Designer is just so easy :-)

image
Figure: Designer properties on the combobox

I have 2 Bindingsources, the Master-Bindingsource and the the Detail-Bindingsource.
I choose the Combobox and set the different properties (DataSource, ValueMember, DisplayMember)

  • I set the ValueMember to the primary key of the Detail-Bindingsource and
  • I set the SelectedValue (Databindings) to the Master-Bindingsource.Doctor (= Entity class)

  image
Figure: Combobox properties in Designer

Problem on runtime

I get the following error

Invalid cast from System.Int32 to ClientName.Business.Entities.Doctors

Reason: The Primary key (Int32) doesn’t fit into the Entity property of the Master-Table (entity)

image 
The problem is: the Entity Framework hides the foreign-key from me (DoctorsId).
I cannot bind to it in the Designer!

How to solve that?

Solution
Don’t use Databinding.
There is no easy way of converting a primary key (Int32) to the actual Entity, with that Integer.
So, do it manually! (AAAAAARRRRRRRGGGGGHHHHHH)

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //HACK: AARRRGHHH: Why I have todo this manually??
            // With other Objects or Datasets we can do this in Designer
            Doctors preferredDoctor = comboBox1.SelectedValue as Doctors;
            if (preferredDoctor != null)
            {
                if (CurrentPatientFromBindingSource != null)
                {
                    CurrentPatientFromBindingSource.Doctor = preferredDoctor;
                }
            }
        }

private void LoadDoctors()
        {
            doctorsBindingSource.DataSource = patientsBL.GetDoctors();

            //HACK: Arrggghhh: Why do I have todo this manually?
            comboBox1.SelectedItem = CurrentPatientFromBindingSource.Doctors;
        }

Todo: Investigate if Linq to Entites provides a flag to configure: Show Foreign Key property for entity

Entity Framework: Why not use Bindingsource.AddNew for creating new objects...

Assuming that you have a Detail Form with a Bindingsource, and the Bindingsource has as Datasource a IQueryable or something derived from that.

image BAD

If you use the Bindingsource to create new objects like this:
      bindingSource.AddNew(); 
your record is detached, and your business rules fire on Save (probably to late for Winforms)

image BETTER

Use
      bindingSource.DataSource = Business.AddNewObject(); 
Your record is attached, and business rules fire OnChange

Assuming you have a Business method like this.

      public Patients AddNewObject()
      {
          MyObject p = new MyObject ();
          // SetDefaultValues(p);
          DBConnection.AddToMyObject(p);
          return p;
      }

Latest Posts

Popular Posts