我如何使用LINQ2SQL分享ASP.NET MVC在各个模型库数据上下文 [英] How do I 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屋!
查看全文