For the last month or so I have been helping out with a medium .NET windows forms application that uses Linq to SQL for it’s ORM. It had been a while since I last used Linq to SQL, so I thought it would be a good time to refresh my skills and write a proof of concept application, one that used Linq to SQL to create, read, update and delete records.
The model consists of four classes and is shown in the following figure.
Linq to SQL Model Diagram
The Book object contains references to each of the Genre, Publisher and Author objects. In this contrived example, a Book must have one and only one Author, Genre and Publisher.
Early one in this prototype, it became apparent that it was important to manage the lifetime on the Linq to SQL DataContext. Rich Strahl has an excellent post on managing the lifetime of DataContext. In this application, the Linq to SQL DataContext is abstracted within a BookRepository class and a singleton is used to serve up a reference to the repository. The following listing shows how this singleton is implemented.
8 public sealed class Repository
9 {
10
11 static BooksRepository _bookRepository = null;
12 static string connectionString;
13
14 private Repository() { }
15
16 public static void ConnectionString(string cs) { connectionString = cs; }
17
18 public static BooksRepository BookRepository(Boolean create)
19 {
20 if (connectionString == null)
21 throw new ApplicationException("Need to set connection string for Repository");
22 if (!create && _bookRepository != null) return _bookRepository;
23 else
24 {
25 _bookRepository = new BooksRepository(connectionString);
26 return _bookRepository;
27 }
28 }
29
30 }
The BookRepository method has a single parameter and decides whether to return a new BooksRepository or to return the existing BooksRepository, remember the BooksRepository abstracts the DataContext. Each call to Repository.BookRepository(false) returns the same BooksRepository and therefore uses same DataContext.