Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架、存储库模式_C#_Asp.net Mvc 3_Entity Framework 4_Repository Pattern - Fatal编程技术网

C# 实体框架、存储库模式

C# 实体框架、存储库模式,c#,asp.net-mvc-3,entity-framework-4,repository-pattern,C#,Asp.net Mvc 3,Entity Framework 4,Repository Pattern,我尝试使用实体框架-存储库模式。(Asp.net C#,EF4) 我为每个DB表创建存储库。但是,当我连接表时,会发生一个错误,即 “指定的LINQ表达式包含对与不同上下文关联的查询的引用。” 为了避免出现错误消息,我将所有内容放在一个类中,如下所示: public class WebOrderRepository { private DbEntities context = new DbEntities(); //Web.config <add name="DBEntities"

我尝试使用实体框架-存储库模式。(Asp.net C#,EF4)

我为每个DB表创建存储库。但是,当我连接表时,会发生一个错误,即

“指定的LINQ表达式包含对与不同上下文关联的查询的引用。”

为了避免出现错误消息,我将所有内容放在一个类中,如下所示:

public class WebOrderRepository
{
    private DbEntities context = new DbEntities(); //Web.config <add name="DBEntities" connectionString=" ...

    public IQueryable<WEBORDERHD> WebOrderHds
    {
        get { return context.WEBORDERHDs; }
    }

    public IQueryable<WEBORDERLN> WebOrderLns
    {
        get { return context.WEBORDERLNs; }
    }
}
我试图将上下文定义为静态的

protected static ShkAdsEntities context = null;
public Repository()
{
    if (context == null)
    {
    context = new ShkAdsEntities();
    }
}
然后,另一个错误发生了

Sequence contains more than one element
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Sequence contains more than one element

Source Error:


Line 116:        {
Line 117:            WebOrderHdRepository webOrderHdRepository = new WebOrderHdRepository();
Line 118:            WebOrderLnRepository webOrderLnRepository = new WebOrderLnRepository();  <== ERROR POINT
Line 119:
Line 120:            var result = (from x in webOrderHdRepository.WebOrderHds
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Source Error:


Line 114:        {
Line 115:            using(WebOrderHdRepository webOrderHdRepository = new WebOrderHdRepository())
Line 116:            using (WebOrderLnRepository webOrderLnRepository = new WebOrderLnRepository())
Line 117:            {
Line 118:
但是发生了一个错误

Sequence contains more than one element
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Sequence contains more than one element

Source Error:


Line 116:        {
Line 117:            WebOrderHdRepository webOrderHdRepository = new WebOrderHdRepository();
Line 118:            WebOrderLnRepository webOrderLnRepository = new WebOrderLnRepository();  <== ERROR POINT
Line 119:
Line 120:            var result = (from x in webOrderHdRepository.WebOrderHds
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Source Error:


Line 114:        {
Line 115:            using(WebOrderHdRepository webOrderHdRepository = new WebOrderHdRepository())
Line 116:            using (WebOrderLnRepository webOrderLnRepository = new WebOrderLnRepository())
Line 117:            {
Line 118:
我认为它试图处理两次,但我不知道如何修复代码

有谁知道,请告诉我~


谢谢

您可以将异常追溯到此语句:

var result = (from x in webOrderHdRepository.WebOrderHds
      join u in webOrderLnRepository.WebOrderLns on x.OrderNo equals u.OrderNo
      select new {x.OrderNo}).SingleOrDefault();
错误发生在-您的集合有多个结果。查看MSDN文档以确定是否应改用

特别是关于
SingleOrDefault
行为,MSDN解释(重点添加):

返回序列的唯一元素,如果 序列为空如果存在更多异常,此方法将引发异常 序列中有多个元素

关于DbContext,您应该能够拥有单独的存储库,只需确保每个存储库使用相同的context对象即可。我猜(在没有看到原始实现的情况下)每个存储库都实例化了自己的上下文对象。我看不出您当前的实现有任何特殊问题,尽管有些人可能会建议如下(未经测试):

更新:

如果您确实尝试了我上面演示的存储库测试,您将需要进行一些重构。它不适用于类的当前状态。这将是一个不同的问题,你需要张贴。上面的代码片段只是查询的示例。正如@Florim Maxhuni所建议的,依赖注入(DI)确实是一条可行之路……这取决于您的需求和时间限制。如果您的DbContext有问题,这将是另一个问题,应该在新的线程中发布。:)

每个存储库创建自己上下文的方法是错误的。相反,必须将上下文注入到存储库中,构造函数注入在这里非常有效


通过这种方式,您可以完全控制上下文以及在存储库之间共享上下文。例如,在web应用程序中,您可以拥有一个具有单个请求生命周期的上下文。

Aha!这个错误影响了我的问题的目的:(您认为存储库代码(带有静态变量)吗可以吗?我可以在我的项目中使用它吗?您可以使用受保护的static,而不是将上下文传递给每个存储库,但我不确定处置和重新实例化中的含义。如果using子句从您应该使用的最内部的“using”开始,那么将调用Dispose方法(然后您可以为每个请求创建DBContext),这样您就不会为每个存储库创建DBContext(这会降低web页面的速度)。数据库上下文当然应该在存储库之间共享。在ASP.NET应用程序中,一种常见的做法是每个HTTP请求有一个上下文。这需要创建一个实现IHttpModule接口的HTTP模块类,在请求开始时初始化上下文,并将其存储在HttpContext.Items中。最后IoC容器还可以选择使用HTTP请求生存期初始化对象。
var result = (from x in webOrderHdRepository.WebOrderHds
      join u in webOrderLnRepository.WebOrderLns on x.OrderNo equals u.OrderNo
      select new {x.OrderNo}).SingleOrDefault();
  public ActionResult repositoryTest() {
     ActionResult actionRes = default(ActionResult);

     using (ShkAdsEntities context = new ShkAdsEntities())
     using (WebOrderHdRepository webOrderHdRepository = new WebOrderHdRepository(context))
     using (WebOrderLnRepository webOrderLnRepository = new WebOrderLnRepository(context)) {

        var result = (from x in webOrderHdRepository.WebOrderHds
                      join u in webOrderLnRepository.WebOrderLns on x.OrderNo equals u.OrderNo
                      select new { x.OrderNo }).SingleOrDefault();

        actionRes = Content(result.OrderNo);
     }

     return actionRes;
  }