【问题标题】:EntityFramework DBContext FirstOrDefault closes connectionEntityFramework DBContext FirstOrDefault 关闭连接
【发布时间】:2014-02-08 03:02:36
【问题描述】:

我有点像 junio 程序员,所以我需要了解这一点。我正在使用 EntityFramework 5。我们实现了一个存储库类,它继承了 DbContext。调用 FirstOrDefault 方法时,如果没有返回值,EntityFramework 将关闭连接。这使代码制动,抱怨 dbContext.Database.Connection.ServerVersion 为空。事实上,连接状态是“关闭”。我实际上是在注入存储库来测试服务,而不使用 Ninject 等。这就是为什么会这样吗?

这是我注入存储库的地方:

IRepository<stock_queues> repo = new DbContextRepositoryEcom<stock_queues>(new DbContextFactory<eComEntities>(new eComEntities()));

        StockFlashService service = new StockFlashService(repo, new PartsService(), new UserService());

        service.AddToStockFlashQueue("asfsdfgvsdf");

这是我实际运行代码的地方(在不同的项目中):

  public StockFlashService(IRepository<stock_queues> queues, IPartsService parts, IUserService users)                     
    {
        this._QueuesRepo = queues;          
        this._PartsService = parts;
        _UsersService = users;
      //  userId = _UsersService.GetUser().UserId;
        userId = 30; //FOR TESTING ONLY !!
    }

 public void AddToStockFlashQueue(string key)
    {            
        stock_queues sq = new stock_queues();
        sq.partnumber = key;
        sq.userID = userId;
        sq.timestamp = DateTime.Now;

        // Adds new entry to Stock Flash queue (if required)
        stock_queues part;
        int count = _QueuesRepo.Count();
        if (_QueuesRepo.Count() > 0)
        {               
            part = _QueuesRepo.FirstOrDefault(f => f.userID == sq.userID && f.partnumber == sq.partnumber); // THIS IS WERE IT ALL BRAKES

        }
}

我正在使用控制台应用程序来测试服务并注入依赖项。托管此服务的项目(不是 Windows / Web 服务,但实际上是执行所有魔术的逻辑)是一个 MVC 应用程序。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-4 dependency-injection


    【解决方案1】:

    FirstorDefault 在没有值时返回 null - 如您的情况。先检查null,然后赋值给'part'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      相关资源
      最近更新 更多