3

I have a form that I use for both editing and inserting new users into a database. I use Entity Framework 6. All my controls (textboxes and one combobox) are bound to specific binding sources so when I update an entity with:

context.user.add(user); 
context.Save();

my UI changes. And vice-versa. Now, updating works fine, but I have some problems with inserting of new users. Currently a data grid view has it datasource set, and I have disabled adding rows by clicking on a grid view directly (because I want that part to go through the form):

tasks window

Okay, so far so good. Now when I want to add a new user, I do this:

myDataSource = context.user.Local.ToBindingList();
 myDataSource.AllowNew = true;

and later on:

myDataSource.AddNew();

After calling AddNew() the blank row is added to a grid view, and when I insert values in my form, everything shows up automatically in the grid view.

The thing is, I can't really persist this data into a database. If I do:

context.Save();

nothing happens. I guess because the newly created entity by the AddNew() method is not attached to the current context. But I don't have a reference to it to attach it.

I guess that AddNew() creates a new entity, right? And adding it to the datasource. Correct me if I am wrong.

So how to save changes in this case?

Whirlwind
  • 14,286
  • 11
  • 68
  • 157

1 Answers1

0

I have a similar issue with getting an added record persisted to the database. I had same basic setup, using .Load, and setting the binding source data source = .Local.ToBindingList() And found an odd fix to the issue. So under my binding navigator save event, this is the only way I could get newly added records to make it to the database. The last ResetBindings call is just so that the Identity Id shows it's actual DB value instead of zero.

    private void mapBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        mapBindingSource.EndEdit();  
        mapBindingSource.ResetBindings(false);
        mapBindingSource.EndEdit();
        _db.SaveChanges();
        mapBindingSource.ResetBindings(false);
    }
Dole
  • 9
  • 2