Page 1 of 1

Best Practices

Posted: Mon 20 Jun 2011 15:52
by JMax
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

Posted: Thu 23 Jun 2011 16:08
by StanislavK
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 ... ntext.aspx

Posted: Thu 23 Jun 2011 19:19
by JMax
Thank you