使用LINQ2SQL在ASP.NET MVC中的各种模型存储库之间共享数据上下文 [英] Share a data context across various model repositories in ASP.NET MVC using LINQ2SQL
本文介绍了使用LINQ2SQL在ASP.NET MVC中的各种模型存储库之间共享数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用程序中有2个存储库,每个存储库都有自己的datacontext对象.
I have a 2 repositories in my application each with their own datacontext objects.
最终结果是我试图将从一个存储库中检索到的对象附加到从另一存储库中检索到的对象,这会导致异常.
The end result has me attempting to attach an object retrieved from one repository to an object retrieved from a different repository which results in an exception.
推荐答案
使用构造函数注入将DataContext注入到每个存储库中:
Use Constructor Injection to inject the DataContext into each Repository:
public class MyRepository : IMyRepository
{
private readonly DataContext dataContext;
public MyRepository(DataContext dataContext)
{
if(dataContext == null)
{
throw new ArgumentNullException("dataContext");
}
this.dataContext = dataContext;
}
// implement MyRepository using this.dataContext;
}
这允许您以任何必需的方式共享或不共享DataContext.
This allows you to share or not share the DataContext in whichever way is necessary.
这篇关于使用LINQ2SQL在ASP.NET MVC中的各种模型存储库之间共享数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文