What is the preferred practice of using linq2sql (in asp.net mvc applications): create a "singleton" for the DataContext , for example:
partial class db { static db _db = new db(global::data.Properties.Settings.Default.nanocrmConnectionString, new AttributeMappingSource()); public static db GetInstance() { return _db; } }
or get a new instance if needed in using :
using (db _db = new db()) { ... }
using using leads to some restrictions in the code. therefore, I prefer to use singleton one. is this a strange practice?
UPD :
explanation why i use singleton:
public class UserGroupRepository { public static IQueryable<Group> RolesFor(string username) { User user = UserRepository.WithUsername(username); return from g in db.GetInstance().Groups join ug in db.GetInstance().UsersGroups on g.Id equals ug.GroupId where ug.UserId == user.Id select g; } }
I have this method. because of this, returns IQueryable - I can continue to compose a query without executing it, so here only a lazy result is returned.
if I rewrote the same code with using - I will not be able to return IQueryable (because db will be deleted and IQueryable will be lost too), and I would change it to List. and now this method will return a "huge" list from which I will filter data by the previous function.
I hope I will describe in sufficient detail.
singleton linq-to-sql
zerkms
source share