Linq2Sql Refresh DataContext

Hi experts!

So I am writing a relatively simple WinForms application for our companies inventory purposes. The database has three tables (Product, Team, and ErrorLog). Team has a one to many relationship with Product. I decided to use Linq2Sql as my ORM. I am used to using NHibernate in ASP.Net so it is quite different.

I have a Main form where a user can view available Teams, or select to create a new team.

Display available Teams in MainForm
        private void FrmProductInventoryMain_Load(object sender, EventArgs e)
        {
            try
            {
                using (dbContext = new ProductInventoryDataContext())
                {
                    this.contextBindingSource = new BindingSource { DataSource = dbContext.Teams.OrderBy(x => x.Name) };

                    cboAllTeams.ValueMember = "Id";
                    cboAllTeams.DisplayMember = "Name";
                    cboAllTeams.DataSource = contextBindingSource;

                    lblMemberOneData.DataBindings.Add("Text", contextBindingSource, "MemberOne");
                    lblMemberTwoData.DataBindings.Add("Text", contextBindingSource, "MemberTwo");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Sorry, an unexpected error occured while trying to connect to the database",
                                "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

Open in new window


I am able to create the new team and it is added to the database with no issues.

Create New Team in Create Team Form
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateMemberOne() || !ValidateMemberTwo()) return;

            // form is valid
            using (dbContext = new ProductInventoryDataContext())
            {
                dbContext.Teams.InsertOnSubmit(new Team
                    {
                        Name = lblTeamNumber.Text,
                        MemberOne = txtNewMemberOne.Text.Trim(),
                        MemberTwo = txtNewMemberTwo.Text.Trim()
                    });

                dbContext.SubmitChanges();
            }

            this.Close();
        }

Open in new window


However, when the "Create Team" form closes, your are left with the "Main Form" which displays the available teams.

I am not sure how to go about updating the Main Form after a new Team has been created, save a last ditch option where I close the main form and reopen it...

I have been reading up as much as possible on how to manage my DataContext, and there seems to be a lot of discussion out there about the best way, or best practice.

Any suggestions ??
I_sAsked:
Who is Participating?
 
käµfm³d 👽Commented:
You can use Show if you prefer; it just means you have to do a bit more work to ensure the update happens after the 2nd form closes. Show is non-blocking; ShowDialog is blocking. If using Show, you could have a callback function that would get executed on the FormClosing/FormClosed event of the 2nd form. It just depends on the needs of your app. (ShowDialog would probably be a bit cleaner.)
0
 
käµfm³d 👽Commented:
I'd be careful keeping a global reference to a DataContext object. A DataContext is supposed to represent a "unit of work". I acknowledge that you are wrapping your DataContext with a using, but keeping a class-level reference to the DC is misleading to others. A class-level variable implies, "use me anywhere within this class." However, since your using implicitly calls Dispose, someone else maintaining the code (or even yourself at some later date) might not realize that the object is being disposed wherever it is being used, and they may try to use the class level variable after the object has been disposed, yield an ObjectDisposedException.

You'll need to rebind your controls after the update to the DC. The DC is not a data store for the DB data; rather it is a bridge between your code and the DB. Query the DC again after you submit your changes.
0
 
I_sAuthor Commented:
Ok, that makes sense. I will remove the class-level context variable. So instead I should create a new local instance per unit of work and then dispose of it?

Also, How would I go about updating the DC when closing the "Create Team" form? I am having trouble wrapping my head around it. In a web app its easier because the DC would be re-initialized between http requests.
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
käµfm³d 👽Commented:
You're not updating the DC--you're updating the DB. The DC is tracking the changes you made to the entity ( db.Teams ). When you call SubmitChanges, the DC submits anything that has been modified (including the addition of new entities or the removal of existing entities) back to the DB. This is why I say that you need to requery the DB to get the updates. You could add a bit of code which would requery the DB (via the DC) after the line that shows the second form--assuming you are using ShowDialog and not Show.
0
 
I_sAuthor Commented:
Ah, well I am using .Show(), but can easily modify that to use .showDialog(). I guess I did not understand the difference between the two. I will try that.
0
 
I_sAuthor Commented:
Worked perfectly.

Had to remove any current DataBindings, and then requery the database. Also used .ShowDialog() rather than .Show()

Thanks for your help!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.