I know the difference between the Entity Framework connected mode vs disconnected mode. In connected mode we do all the stuff inside one single DbContext instance. In disconnected mode we do the stuff and then attach the Entity to a new DbContext instance.
My problem is that I - for a specific reason - had to create the DbContext instance globally in the form class without disposing it (I'm disposing the form after closing) and I'm confused and want to review my code and determine if it's a connected or a disconnected mode and if it's good practice to do this:
public partial class FrmProducts : MetroForm
{
public FrmProducts()
{
InitializeComponent();
}
//The DbContext:
FDB.MFdb db = new FDB.MFdb();
private void sfButton1_Click(object sender, EventArgs e)
{
try
{
//New row:
if (txtID.Text.Trim() == "")
{
short maxID, newID;
if (db.Products.Count() > 0)
{
maxID = db.Products.Max(p => p.PID);
newID = ++maxID;
}
else
newID = 1;
//New Database Entity:
FDB.Product px = new FDB.Product();
//Set entity data:
px.PID = newID;
px.P_Code = txtCode.Text;
px.P_Name = txtName.Text;
px.P_Purchase_Price = Convert.ToDecimal(txtPurchase.Text);
px.P_Sale_Price = Convert.ToDecimal(txtSale.Text);
px.P_Notes = txtNotes.Text;
//Add entity to DbContext:
db.Products.Add(px);
db.SaveChanges();
//This is a BindingSource Control:
binSrc.Add(px);
}
else
{
//Edit row:
int pid = Convert.ToInt16(txtID.Text);
var row = db.Products.Single(b => b.PID == pid);
row.P_Code = txtCode.Text;
row.P_Name = txtName.Text;
row.P_Purchase_Price = Convert.ToDecimal(txtPurchase.Text);
row.P_Sale_Price = Convert.ToDecimal(txtSale.Text);
row.P_Notes = txtNotes.Text;
db.SaveChanges();
}
//Reset BindingSource to reflect updated data:
binSrc.ResetBindings(false);
}
catch (Exception ex)
{
//Discard Db Changes if error occurred:
foreach (var ent in db.ChangeTracker.Entries())
{
if (ent.State == EntityState.Modified)
{
ent.State = EntityState.Unchanged;
}
else if (ent.State == EntityState.Added)
{
ent.State = EntityState.Detached;
}
}
MessageBox.Show(ex.Message + "\nInner Exception:\n" + ex.InnerException);
}
}
using { }and do all the stuff inside it. Here I didn't follow that practice and made theDbContextat form level which made me confused. Thanks for reply. \$\endgroup\$