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:
your record is detached, and your business rules fire on Save (probably to late for Winforms)

image BETTER

      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);
          return p;


Anonymous said...

Thanks for this! You saved me many days of tearing my hair out. This information was not easy to find.



Anonymous said...

This is great!!
I'm glad that I've found your suggestion *while* implementing add functionality.


Ariel Abaca said...

I have a Windows form with a DataGridView.
The DataGridview is bound to a BindingSource.
The BindingSource's DataSource is one of my Entity FrameWork's entities.

private void FormPrueba_Load(object sender, EventArgs e)
this.bindingSource1.DataSource = Globals.DataBaseContext.Calles;

I can not understand how to make the changes in the DataGridView appear in the
BindingSource nor the database.
I tried using this.bindingSource1.EndEdit() in multiple event handlers.
I use my DataBaseContext.GetChanges() for discovering if there are changes.
It never finds a change.

Maybe I am losing something in the middle.
Can you help me, please ?

Thanks in advance.
Ariel. (abacrotto@hotmail.com)

Peter Gfader said...

Hi Ariel

What is "Globals.DataBaseContext.Calles"

Something like this should work AFAIR

db = new NorthwindDataContext();
var employeeQuery = from employee in db.Employees
orderby employee.FirstName
select employee;
employeeBindingSource.DataSource = employeeQuery;

samio said...

Thanks for this , please could you continue with Ariel's case (with NorthwindDataContext) to show how we can write code for addNew button in databindNavigator. And how is it possible to set some values in the newly added row before persisting data, specialy to fill related values to foreign keys.

Post a Comment

Latest Posts

Popular Posts