What is the best practice for setting up my DataContext for easy access in my extended LinqToSql classes?
For example, I have a User object in my dbml, and I want to add methods to this class as follows:
Partial Public Class User Public Function GetUser(ByVal UserID as Integer) as User 'Do Work End Function End Class
To access my DataContext, I would have to declare it inside the method as follows:
Partial Public Class User Public Function GetUser(ByVal UserID as Integer) as User Dim dc as New MyDataContext() Return (From u in dc.Users Where u.ID = UserID).Single() End Function End Class
I would not want to do this for each method. Usually (if I did not extend the LinqToSql dbml classes), I could just do this:
Partial Public Class User Private dc as MyDataContext Public Sub New() dc = new MyDataContext() End Sub Public Function GetUser(ByVal UserID as Integer) as User Return (From u in dc.Users Where u.ID = UserID).Single() End Function Public Function GetAllUsers() as IEnumerable(Of User) Return From u in dc.Users End Function 'etc... End Class
This will allow me to access the datacontext for each method without having to declare it every time. But of course you cannot do this because dbml already has a constructor. And adding code to dbml is always overwritten if anything changes.
Does anyone have any good ideas on how to save redundant code here?
TIA!
EdenMachine Feb 14 '09 at 17:23 2009-02-14 17:23
source share