Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

.net - LinqToSql declare and instantiate DataContext best practice?

What's the best practice in terms of setting up my DataContext for easy access in my extended LinqToSql classes?

For example, I have a "User" entity in my dbml and I want to add methods to that class like so:

Partial Public Class User

    Public Function GetUser(ByVal UserID as Integer) as User
         'Do Work
    End Function

End Class

In order to access my DataContext I'd have to declare it inside the method like so:

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'd like to not have to do that for every single method. Normally (if I weren't extending 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 would allow me to access the datacontext for each method without having to declare it newly each time. But of course you can't do that because the dbml already has a constructor. And adding code into the dbml always gets overwritten if anything ever changes.

Anyone have any good ideas on how to save myself some excess code here?

TIA!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, make sure you are disposing your DataContext when you're done! He can be a heavy little bastard (edit not heavy to instantiate, but heavy to keep around if you keep using it without disposing); you don't want old DataContexts hanging around in memory.

Second, the DataContext is intended to represent a single logical transaction. E.g. you should create a new one every time you want to start a new transaction, and get rid of it when that transaction is complete. So for your purposes, that is probably the scope of the GetUser method. If you have a series of DB calls that need to be made as a group, they should all use the same DC before getting rid of it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...