Best Practices

Best Practices

Postby JMax » Mon 20 Jun 2011 15:52

Good Morning,

I am working on implementing the dotConnect for MySQL. It seems as if it will save an impressive amount of time, and make coding much cleaner and legible. I am curious as to the best method for putting LINQ queries into functions. In LINQ, you have to have a DataContext that you query against. Should I create a new instance of my DataContext each time a function is called, or should I pass a previously created instance of it to the function to query against it.

For example, is it the best to do this?
Code: Select all
public static ProgramContext.Member rMember (int id) {
     ProgramDataContext db = new ProgramDataContext();

     return (from p in db.Members
                where p.Id == id
                select p).First();
}


or this?

Code: Select all
public static ProgramContext.Member rMember (int id, ProgramDataContext db) {
     return (from p in db.Members
                where p.Id == id
                select p).First();
}



Thank you!

JMax
JMax
 
Posts: 4
Joined: Thu 16 Jun 2011 22:29

Postby StanislavK » Thu 23 Jun 2011 16:08

Generally, DataContext is considered to be a light-weight object that should be re-created each time a new operation is performed. The main reason for this is that the data cached in DataContext may become stale right after it was retrieved from the database. However, it may be reasonable to use a single DataContext instance for querying the server, provided that you are not going to update data via this instance.

For more information about the DataContext lifetime, please refer, e.g., to the following article:
http://blogs.msdn.com/b/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx
StanislavK
Devart Team
 
Posts: 1710
Joined: Thu 03 Dec 2009 10:48

Postby JMax » Thu 23 Jun 2011 19:19

Thank you
JMax
 
Posts: 4
Joined: Thu 16 Jun 2011 22:29


Return to dotConnect for MySQL