tags:

views:

82

answers:

4

Would creating another datacontext in the GetData3() method lead to problems?

  public void SetoFDataMethods()
  {
    using (DataContext DC= new DataContext())
    {

        var d1=DC.GetData1();
        var d2=DC.GetData2();
        var d3=DC.GetData3();

        display(d3);

    }
  }


  public result GetData3()
   {
        If (conditionA)
        {
               using (DataContext newContext=new DataContext())
               {
                    var result= newContext.GetData4();
                   return result;
               }
        }        
   }
+3  A: 

No I don't think that it would necessarily create problems, but it could create confusion. Each context will be independent and won't share transactions unless you explicitly code that in. I do something similar where I use multiple data contexts, one for auditing and the other for the actual data, but they are separate and don't even map the same tables.

My suggestion is to push the data context up one level -- from the method to the class -- so all of the methods in the class can share the same data context. The reason that I didn't do this is that I explicitly wanted to separate the transactions so that I could log both failures and successes via the auditing utility. In places where I am sharing the same data context, I do use it at the instance level rather than the method level.

One advantage of pushing the context up is that you can then easily inject a mock context if you need to for unit testing. Creating a data context inside your method is going to make it difficult to unit test since you don't have an easy way to isolate it from your actual database. I posted a blog entry on mocking/faking the LINQ data context using a wrapper awhile back that may be helpful if you go down this road.

tvanfosson
+1  A: 

Do be aware that objects retrieved from one context are tied to that context unless you do some explicit magic to the contrary. As it stands, attempting to, say, delete an object from a context other than the one it was retrieved from will throw an exception.

JoshJordan
+1  A: 

I would suggest that you send the DataContext as a parameter and use the same DataContext.

Shiraz Bhaiji
+1  A: 

Not easily by default. You would have to detach entities bound to the context in order to use them on another data context. A simple solution to this would be creating a Unit of Work pattern.

Sergey