LinqToSql声明和实例的DataContext最佳做法?实例、做法、声明、LinqToSql

2023-09-02 10:28:13 作者:不信命只信双手去苦拼

什么是在建立我的DataContext为方便在我的扩展LinqToSql类方面的最佳实践?

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

例如,我在我的dbml用户的实体,我想的方法添加到类像这样:

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

为了访问我的DataContext我不得不像这样的方法内声明它:

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

我想没有这样做,每一个方法。通常情况下(如果我不延长LinqToSql的dbml类),我可以做到这一点:

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

这将使我访问DataContext的每个方法,而不必每次新的声明。当然,你不能这样做,因为DBML已经有一个构造函数。并增加code到DBML始终被覆盖如果有什么都没有改变。

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.

任何人有关于如何拯救自己一些多余的code有什么好想法?

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

TIA!

推荐答案

首先,确保你处理你的DataContext时,你就大功告成了!他可以是一个沉重的小混蛋(修改不重来实例化,但重信守约,如果你继续使用它而不处理);你不想老DataContexts在内存中徘徊。

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.

其次,在DataContext的目的是重新present一个逻辑事务。例如。你应该要开始一个新的事务每次创建一个新的,并摆脱它时的是的交易就完成了。因此,对于你而言,这是的也许的的的getUser 方法的范围。如果你有一系列需要被制成一组DB的电话,他们都应该摆脱之前使用相同的DC。

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.