I work on windows form with entity framework 5.
I have a datagridview to record new sales and a save button to save changes on my entities. But before saving the entities, I create some new stock objects. I have another gridview that looks at my stock but which is readonly.
My issues are the followings:
- The sales and stock are updated in my database but while the gridview for sales show the new sales, the gridview for stock doesn't update to show the new stock
- If there was an error on adding a new sale (say a foreign key error when inserting into the database) then after correcting the error and re-clicking on save, the sale is inserted once but the stock twice (or as many times as I had en error message)
I tried to create my stock through the createobject method rather than just with the new keywork but the problems remain.
Here is my saveButton click code
private void SaveButton_Click(object sender, EventArgs e)
{
try
{
var txnsGr = (IEnumerable<TransactionsGroupee>)this.achatsGroupeeBindingSource.DataSource;
foreach (var txnGr in txnsGr)
if (txnGr.EntityState == EntityState.Detached)
ge.TransactionsGroupees.AddObject(txnGr);
var localTransactions = ge.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Where(ent => ent.Entity is Transaction).Select(ent => ent.Entity as Transaction);
var achats = localTransactions.Where(x => x.TransactionsGroupee.sens == (int)Sens.Achat);
foreach (Transaction txn in achats)
{
for (int i = 0; i < txn.quantite; i++)
{
Stock stock = ge.CreateObject<Stock>();
stock.Agence1 = agence;
stock.Transaction = txn;
ge.Stocks.AddObject(stock);
}
}
ge.SaveChanges();
}
catch (Exception ex)
{
StringBuilder err = new StringBuilder(ex.Message);
if (ex.InnerException != null)
err.AppendLine().Append(ex.InnerException.Message);
MessageBox.Show(err.ToString());
}
}
Note that my sales (from two gridviews in a master/details configuration actually) where somehow detached and I have to attach them back first but hopefully this is not related to the issues described above.