Handling Entity Framework in connected mode within Windows Forms












0












$begingroup$


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);
}
}









share|improve this question









New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    $endgroup$
    – Jamal
    yesterday










  • $begingroup$
    in connected mode we do all the stuff inside one single DbContext instance -- Doesn't that answer you own question is it a connected or a disconnected mode? Whether or not it's good practice is opinion-based.
    $endgroup$
    – Gert Arnold
    17 hours ago












  • $begingroup$
    @GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use using { } and do all the stuff inside it. Here I didn't follow that practice and made the DbContext at form level which made me confused. Thanks for reply.
    $endgroup$
    – Ahmed Suror
    8 hours ago
















0












$begingroup$


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);
}
}









share|improve this question









New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    $endgroup$
    – Jamal
    yesterday










  • $begingroup$
    in connected mode we do all the stuff inside one single DbContext instance -- Doesn't that answer you own question is it a connected or a disconnected mode? Whether or not it's good practice is opinion-based.
    $endgroup$
    – Gert Arnold
    17 hours ago












  • $begingroup$
    @GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use using { } and do all the stuff inside it. Here I didn't follow that practice and made the DbContext at form level which made me confused. Thanks for reply.
    $endgroup$
    – Ahmed Suror
    8 hours ago














0












0








0





$begingroup$


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);
}
}









share|improve this question









New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




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);
}
}






c# .net database entity-framework entity-framework-core






share|improve this question









New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 27 mins ago









Jamal

30.3k11119227




30.3k11119227






New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Ahmed SurorAhmed Suror

11




11




New contributor




Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Ahmed Suror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    $begingroup$
    The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    $endgroup$
    – Jamal
    yesterday










  • $begingroup$
    in connected mode we do all the stuff inside one single DbContext instance -- Doesn't that answer you own question is it a connected or a disconnected mode? Whether or not it's good practice is opinion-based.
    $endgroup$
    – Gert Arnold
    17 hours ago












  • $begingroup$
    @GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use using { } and do all the stuff inside it. Here I didn't follow that practice and made the DbContext at form level which made me confused. Thanks for reply.
    $endgroup$
    – Ahmed Suror
    8 hours ago














  • 1




    $begingroup$
    The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    $endgroup$
    – Jamal
    yesterday










  • $begingroup$
    in connected mode we do all the stuff inside one single DbContext instance -- Doesn't that answer you own question is it a connected or a disconnected mode? Whether or not it's good practice is opinion-based.
    $endgroup$
    – Gert Arnold
    17 hours ago












  • $begingroup$
    @GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use using { } and do all the stuff inside it. Here I didn't follow that practice and made the DbContext at form level which made me confused. Thanks for reply.
    $endgroup$
    – Ahmed Suror
    8 hours ago








1




1




$begingroup$
The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
$endgroup$
– Jamal
yesterday




$begingroup$
The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
$endgroup$
– Jamal
yesterday












$begingroup$
in connected mode we do all the stuff inside one single DbContext instance -- Doesn't that answer you own question is it a connected or a disconnected mode? Whether or not it's good practice is opinion-based.
$endgroup$
– Gert Arnold
17 hours ago






$begingroup$
in connected mode we do all the stuff inside one single DbContext instance -- Doesn't that answer you own question is it a connected or a disconnected mode? Whether or not it's good practice is opinion-based.
$endgroup$
– Gert Arnold
17 hours ago














$begingroup$
@GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use using { } and do all the stuff inside it. Here I didn't follow that practice and made the DbContext at form level which made me confused. Thanks for reply.
$endgroup$
– Ahmed Suror
8 hours ago




$begingroup$
@GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use using { } and do all the stuff inside it. Here I didn't follow that practice and made the DbContext at form level which made me confused. Thanks for reply.
$endgroup$
– Ahmed Suror
8 hours ago










1 Answer
1






active

oldest

votes


















2












$begingroup$

It is a best-practice to have a clear separation between UI layer (the forms) and data access, so all your data access logic (opening the connection, issuing quries, closing it etc.) should be handled in a separate class (service) that can be reused by other classes / forms.



This will help you have a single place to handle specific things like logging, reverting changes on error:



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;
}
}
}


Also, EF contexts are typically used for a short period (new + query stuff + save changes + dispose) because a Dispose does not mean a connection close (in most cases) since connection pooling kicks in. So, there is really no significant penalty, but you make sure that there no undisposed context lurking around.



There might be exceptions to this, such as when using a unit of work pattern which uses a connection per "unit of work" (e.g. thread, request), but stick the above for the beginning and you will be fine.



As a conclusion:




  • move all database context logic into a separate class

  • put all context related logic into a using block that ensures context disposal






share|improve this answer









$endgroup$













  • $begingroup$
    The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
    $endgroup$
    – Ahmed Suror
    8 hours ago












  • $begingroup$
    @AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
    $endgroup$
    – Alexei
    2 hours ago











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Ahmed Suror is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214186%2fhandling-entity-framework-in-connected-mode-within-windows-forms%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2












$begingroup$

It is a best-practice to have a clear separation between UI layer (the forms) and data access, so all your data access logic (opening the connection, issuing quries, closing it etc.) should be handled in a separate class (service) that can be reused by other classes / forms.



This will help you have a single place to handle specific things like logging, reverting changes on error:



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;
}
}
}


Also, EF contexts are typically used for a short period (new + query stuff + save changes + dispose) because a Dispose does not mean a connection close (in most cases) since connection pooling kicks in. So, there is really no significant penalty, but you make sure that there no undisposed context lurking around.



There might be exceptions to this, such as when using a unit of work pattern which uses a connection per "unit of work" (e.g. thread, request), but stick the above for the beginning and you will be fine.



As a conclusion:




  • move all database context logic into a separate class

  • put all context related logic into a using block that ensures context disposal






share|improve this answer









$endgroup$













  • $begingroup$
    The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
    $endgroup$
    – Ahmed Suror
    8 hours ago












  • $begingroup$
    @AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
    $endgroup$
    – Alexei
    2 hours ago
















2












$begingroup$

It is a best-practice to have a clear separation between UI layer (the forms) and data access, so all your data access logic (opening the connection, issuing quries, closing it etc.) should be handled in a separate class (service) that can be reused by other classes / forms.



This will help you have a single place to handle specific things like logging, reverting changes on error:



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;
}
}
}


Also, EF contexts are typically used for a short period (new + query stuff + save changes + dispose) because a Dispose does not mean a connection close (in most cases) since connection pooling kicks in. So, there is really no significant penalty, but you make sure that there no undisposed context lurking around.



There might be exceptions to this, such as when using a unit of work pattern which uses a connection per "unit of work" (e.g. thread, request), but stick the above for the beginning and you will be fine.



As a conclusion:




  • move all database context logic into a separate class

  • put all context related logic into a using block that ensures context disposal






share|improve this answer









$endgroup$













  • $begingroup$
    The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
    $endgroup$
    – Ahmed Suror
    8 hours ago












  • $begingroup$
    @AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
    $endgroup$
    – Alexei
    2 hours ago














2












2








2





$begingroup$

It is a best-practice to have a clear separation between UI layer (the forms) and data access, so all your data access logic (opening the connection, issuing quries, closing it etc.) should be handled in a separate class (service) that can be reused by other classes / forms.



This will help you have a single place to handle specific things like logging, reverting changes on error:



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;
}
}
}


Also, EF contexts are typically used for a short period (new + query stuff + save changes + dispose) because a Dispose does not mean a connection close (in most cases) since connection pooling kicks in. So, there is really no significant penalty, but you make sure that there no undisposed context lurking around.



There might be exceptions to this, such as when using a unit of work pattern which uses a connection per "unit of work" (e.g. thread, request), but stick the above for the beginning and you will be fine.



As a conclusion:




  • move all database context logic into a separate class

  • put all context related logic into a using block that ensures context disposal






share|improve this answer









$endgroup$



It is a best-practice to have a clear separation between UI layer (the forms) and data access, so all your data access logic (opening the connection, issuing quries, closing it etc.) should be handled in a separate class (service) that can be reused by other classes / forms.



This will help you have a single place to handle specific things like logging, reverting changes on error:



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;
}
}
}


Also, EF contexts are typically used for a short period (new + query stuff + save changes + dispose) because a Dispose does not mean a connection close (in most cases) since connection pooling kicks in. So, there is really no significant penalty, but you make sure that there no undisposed context lurking around.



There might be exceptions to this, such as when using a unit of work pattern which uses a connection per "unit of work" (e.g. thread, request), but stick the above for the beginning and you will be fine.



As a conclusion:




  • move all database context logic into a separate class

  • put all context related logic into a using block that ensures context disposal







share|improve this answer












share|improve this answer



share|improve this answer










answered 23 hours ago









AlexeiAlexei

1,442729




1,442729












  • $begingroup$
    The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
    $endgroup$
    – Ahmed Suror
    8 hours ago












  • $begingroup$
    @AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
    $endgroup$
    – Alexei
    2 hours ago


















  • $begingroup$
    The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
    $endgroup$
    – Ahmed Suror
    8 hours ago












  • $begingroup$
    @AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
    $endgroup$
    – Alexei
    2 hours ago
















$begingroup$
The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
$endgroup$
– Ahmed Suror
8 hours ago






$begingroup$
The specific reason for not using Using { } is that I'm binding a DataGridView using a BindingSource to the same global DbContext to make sure that DbContext see all modifications made to the BindingSource, and if I used two different instances of DbContext the changes to BindingSource don't commit to the original data source and vice versa...
$endgroup$
– Ahmed Suror
8 hours ago














$begingroup$
@AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
$endgroup$
– Alexei
2 hours ago




$begingroup$
@AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all).
$endgroup$
– Alexei
2 hours ago










Ahmed Suror is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Ahmed Suror is a new contributor. Be nice, and check out our Code of Conduct.













Ahmed Suror is a new contributor. Be nice, and check out our Code of Conduct.












Ahmed Suror is a new contributor. Be nice, and check out our Code of Conduct.
















Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214186%2fhandling-entity-framework-in-connected-mode-within-windows-forms%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Список кардиналов, возведённых папой римским Каликстом III

Deduzione

Mysql.sock missing - “Can't connect to local MySQL server through socket”