Data Platform Developer Center > Data Platform Development Forums > LINQ to SQL > Dispose and Recreate Linq2Sql DataContext
Ask a questionAsk a question
 

AnswerDispose and Recreate Linq2Sql DataContext

  • Tuesday, November 03, 2009 6:07 PMderski Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,
    Is it possible to destroy and recreate a linq data context while switching the datasource of some binding source behind the scenes to the new context?
    So lets say I have some data bound to an old context

    BindingSource bs = new BindingSource();
    bs.datasource = context.SomeTable;

    //next some weird error happens and I want (well, need) to re-create my linq context
    context = context.DisposeAndRecreate();// some method which closes connection, disposes old context and creates a fresh one.

    now any operation on the bs bound object will throw the objectdisposed exception because the original context is gone.
    Is there a way to on catching that exception to rebind the bs.datasource to the new context? Or maybe instead of destroying the original context I somehow detach everything, and attach fresh objects, something like
    Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues,ALLENTITIES) except instead of refreshing individual entities it gets a clean copy of the context .


    Currently I close all my forms, to recreate the datacontext, seems like maybe there is some workaround to that.

    Thanks a lot,

    Chris

Answers

  • Tuesday, November 03, 2009 9:19 PMd13mr3m1x Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    This may not be of much help but scott gu has a great blog series on linq 2 sql and basically shows all the good things you can with linq 2 sql.

    http://weblogs.asp.net/scottgu/archive/2007/09/07/linq-to-sql-part-9-using-a-custom-linq-expression-with-the-lt-asp-linqdatasource-gt-control.aspx

    That is last part of the series that has links to all 9 other parts.

    Hope this helps with the understanding of linq 2 sql.

    I havent done much work with binding data sources so I couldn't help you there sorry!

    Hope this helps!
  • Wednesday, November 04, 2009 9:34 AMLingzhi SunMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Hi Chris,

     

    Glad to see you again!

     

    Although DataContext is designed to be a short-lived object, we need to use it based on our detailed scenario.  Sometimes, a longer-lived DataContext is also acceptable.  MVP Rick Strahl has one famous article introducing different patterns to use the DataContext, http://www.west-wind.com/weblog/posts/246222.aspx. 

     

    Also, as d13mr3m1x has suggested, Scott Gu’s series articles on LINQ to SQL is really great and helpful. 

     

    I have some little demo projects to bind parent and child tables onto two DataGridViews via two BindingSources.  All the normal insert/update/delete operations can be tracked by the DataContext.  

    ========================================================================
                bs.DataSource = db.ParentTables;

                dataGridView1.DataSource = bs;

                bs2.DataSource = bs;

                bs2.DataMember = "ChildTables";

                dataGridView2.DataSource = bs2;
    ========================================================================

     

    Any problems do you encounter?   Please provide us with detailed information for further investigation. 

     

     

    Have a nice day!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

All Replies

  • Tuesday, November 03, 2009 7:27 PMd13mr3m1x Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hey,

    I don't know if this is relevant to your question but it usually practice to wrap the data context in a using statement for every unit of work.

    Example:

    To query the database:

    using (context db = new context())
    {
       var q = from t in db.Test
                   select t;
    }

    and to insert I would then:

    using (context db = new context())
    {
       Test newTest = new Test()
      
       newTest.Name = "Test";
       newTest.Country = "Canada";
      
       db.Test.InsertOnSubmit(newTest);
       db.SubmitChanges();
    }

    So basically for every unit of work I create a new data context inside a using statement and after the statement is finished the context is disposed of!

    Hopefully this helps and is relevant!
  • Tuesday, November 03, 2009 8:59 PMderski Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks for your reply,
    I think I maybe I took a wrong approach in persisting my linq context as a long lived object. I have some workflows which may require as many as 8 different modal forms to be open and each form queries the current data context for potentially additional information. I need to keep the data in sync between the 8 open forms and selectively commit or cancel changes. Essentially whatever goes on inside the  using {} would potentially last a long time because I need (at least I think I need, never occurred to me to keep a bunch of contexts alive at once, I will have to think about that) to keep the context alive while the workflow finishes.
    This is just some ex.
    I can have objects A,B,C,D
    A has a collection of B objects.
    B has a collection of C objects.
    (etc)
    For each object I may have a lookup and and management form.
    Starting a workflow from object A I may have to create a new A, and Create a bunch of new B's(belonging to A) or add already existing Bs, then Create a bunch of C's (belonging to Bs) etc.
    As the form for each object B,C,D loads, I query the context for additional infomation as required by the form. So when I call B from A, A just kind of waits there for B to finish.

    Are you saying that for each potential form you open up a new data context? And then the context for form A is not really in sync with form B?

    I don't want anything saved until a user actually decides to click accept on a corresponding management form. which requires all these objects, potentially my entire context, to be in memory.
    At the end of the workflow, the user can accept some D's which would only submit to the database  the newly added, updated or deleted D objects without saving any of the the other A,B or C object information, which they can still cancel out of.
    Once they are out of the initial workflow, so they close out the initial Form with A objects the workflow is done, all the changes have been either submitted or rejected and I can safely destroy my data context.

    I have been using linq2sql and binding sources for all my data access.

    Here is an example of how I"m managing all my data.

    For example to get my form A stuff I would do
    bindingSOurceA.datasource = context.GETAObjects; (I bind all controls on my forms to the bindingsource fields)

    //the current A object I'm working with I get from bindingSourceA.current.

    If I want to edit A and its collection of B's I would use a Second Binding Source, 
    BindingSOurce BindingSourceBsBelongingToAs = New BindingSource() and set the datasource to the current A object and datamember to "B"
    which gets the collection of all B's belonging to A's

    Then If I want to submit changes made to be I just call the BindingSourceBsBelongingToAs.endEdit() and context.SubmitChanges()
    This will only push changes in B's because bindingSOurceA.endedit() has not been called so changes would not be pushed into the context.


    I've learned linq2sql on the fly just by trial and error, I don't really know how it should be done.

    If you can give me a pretty simple example, using two objects with one to many relationship, and how to add, edit delete A and its collection of B's that would be awesome.

    I'm just not sure how to wrap the using{} statement across multiple forms.

    Thanks so much.

    Chris






  • Tuesday, November 03, 2009 9:19 PMd13mr3m1x Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    This may not be of much help but scott gu has a great blog series on linq 2 sql and basically shows all the good things you can with linq 2 sql.

    http://weblogs.asp.net/scottgu/archive/2007/09/07/linq-to-sql-part-9-using-a-custom-linq-expression-with-the-lt-asp-linqdatasource-gt-control.aspx

    That is last part of the series that has links to all 9 other parts.

    Hope this helps with the understanding of linq 2 sql.

    I havent done much work with binding data sources so I couldn't help you there sorry!

    Hope this helps!
  • Wednesday, November 04, 2009 9:34 AMLingzhi SunMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Hi Chris,

     

    Glad to see you again!

     

    Although DataContext is designed to be a short-lived object, we need to use it based on our detailed scenario.  Sometimes, a longer-lived DataContext is also acceptable.  MVP Rick Strahl has one famous article introducing different patterns to use the DataContext, http://www.west-wind.com/weblog/posts/246222.aspx. 

     

    Also, as d13mr3m1x has suggested, Scott Gu’s series articles on LINQ to SQL is really great and helpful. 

     

    I have some little demo projects to bind parent and child tables onto two DataGridViews via two BindingSources.  All the normal insert/update/delete operations can be tracked by the DataContext.  

    ========================================================================
                bs.DataSource = db.ParentTables;

                dataGridView1.DataSource = bs;

                bs2.DataSource = bs;

                bs2.DataMember = "ChildTables";

                dataGridView2.DataSource = bs2;
    ========================================================================

     

    Any problems do you encounter?   Please provide us with detailed information for further investigation. 

     

     

    Have a nice day!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
  • Thursday, November 05, 2009 10:32 PMderski Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks for the reply,
    Actually I bind my data exactly how you described, even across multiple forms I attempt to pass all my data into constructors as bindingsource parameters. I  love working with bindingsources, they seem to do 90% of the work for you but on the occasional issues between bindingsources and linq its sometimes hard to figure out how the datacontext gets implicitly updated.
    I try to avoid making any manual inserts or deletes into the datacontext and rely on the bindingsource to keep the data context in sync.
    It works great for me in 95% of cases, I have run into a few minor issues where the datacontext seems to get updated without me explicitly calling the endedit() on the bindingsource, this happens in fairly complex workflows when a lot of new "child" items are created.  I figured out it was actually linq attaching entities in a constructor based on FK constraints but I can have workarounds to the few limited cases. 
    And if I ever get into too much trouble yeah, I just close any open workflows and recreate my context. 
    Thanks for posting the links, I will look at them shortly.

    Chris
  • Thursday, November 05, 2009 10:46 PMderski Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks for the link, its quite a different approach then I've been using, I really like binding sources though I found there seems to be a certain amount of hostility towards them :)
    The site seems to be a pretty decent introduction into linq and specifically for web development which I have not done before but will have to pretty soon so it will be very useful.

  • Friday, November 06, 2009 2:44 PMLingzhi SunMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Chris,

     

    I am glad that the links are helpful for you.  J

     

    If you have any further questions, I am really glad to discuss with you. 

     

    Have a nice weekend!

     

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.