问题描述
我在决定系统中的哪一层应该创建 DataContext 时遇到问题.我读过一本书,说如果不为所有的数据传递相同的 DataContext 对象数据库更新时,它有时会从 DataContext 中抛出异常.这就是为什么我最初在业务层创建 DataContext 的新实例,并将其传递到数据访问层.这样所有更新都使用相同的数据上下文.但这导致了一个设计问题,如果我想将来将我的 DAL 更改为 Non-LinqToSQL,我还需要在业务层重新编写代码.请就此给我一些建议.谢谢.
I have a problem to decide which layer in my system should create DataContext. I have read a book, saying that if do not pass the same DataContext object for all thedatabase updates, it will sometimes get an exception thrown from the DataContext. That's why i initially create new instance of DataContext in business layer, and pass it into data access layer. So that the same datacontext is used for all the updates. But this lead to one design problem, if i wanna change my DAL to Non-LinqToSQL in future, i need to re-write the code in business layer as well. Please give me some advice on this. Thanks.
示例代码
'Business Layer
Public Sub SaveData(name As String)
Using ts AS New TransactionScope()
Using db As New MyDataContext()
DAL.Insert(db,name)
DAL.Insert(db,name)
End Using
ts.Complete()
End Using
End Sub
'Data Access Layer
Public Sub Insert(db as MyDataContext,name As string)
db.TableAInsert(name)
End Sub
推荐答案
作为与 LINQ to SQL 紧密耦合的 DataContext,您绝对应该在 DAL 中创建它.
Being the DataContext tightly coupled to LINQ to SQL, you should definitely create it in the DAL.
看看我提供的答案 有些相关的 SO 问题.它带来了同样的问题,即 DataContext(实体框架中的 ObjectContext)是应该在多个数据库操作中保持活动状态,还是应该临时创建和处置.
Have a look at the answer I provided to this somewhat related SO question. It brings up the same problem of whether the DataContext (ObjectContext in Entity Framework) should be kept alive across multiple database operations, or it should be created and disposed of ad-hoc.
您所指的问题与通过 DataContext 检索的模型对象只能使用相同的 DataContext 实例进行更新.现在,如果原始 DataContext 已被释放,任何将更新的模型对象附加到新 DataContext 实例的尝试都将失败.
The problems you are referring to are related to the fact that model objects retrieved through a DataContext can only be updated using the same DataContext instance. Now, if the original DataContext has been disposed, any attempt to attach an updated model object to a new DataContext instance will fail.
然而,这不一定是一个问题,这取决于您的应用程序的架构.
例如,通过 LINQ to SQL 检索和操作的模型对象正在客户端之间来回序列化(就像在 Web应用程序或 Web 服务),而更新的对象将永远不会与最初检索的对象相同.在这种情况下,它们可以安全地附加到新的 DataContext.
However this isn't necessarily an issue, depending on your application's architecture.
For example, ff the model objects retrieved and manipulated through LINQ to SQL are being serialized back and forth between a client (like in a web application or a web service) than the updated objects will never be the same as the ones that were originally retrieved. In that case they can safely be attached to a new DataContext.
这篇关于哪个层应该创建DataContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!