?
Solved

Linq2Sql Refresh DataContext

Posted on 2012-08-14
6
Medium Priority
?
1,471 Views
Last Modified: 2012-08-14
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 ??
0
Comment
Question by:I_s
  • 3
  • 3
6 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38293812
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
 

Author Comment

by:I_s
ID: 38293892
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38293934
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
Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

 

Author Comment

by:I_s
ID: 38293951
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
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 38293984
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
 

Author Comment

by:I_s
ID: 38293987
Worked perfectly.

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

Thanks for your help!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question