使用IQueryable< TEntity>而是DbSet< TEntity>问题 [英] Using IQueryable<TEntity> instead DbSet<TEntity> problem

查看:91
本文介绍了使用IQueryable< TEntity>而是DbSet< TEntity>问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现下一个问题...我有数据库上下文:

i stumbled to the next problem... I have database context:

// For support unit testing... 
public interface IDbContext : IDisposable
{
   IQueryable<Hardware> Hardwares { get; }
   IQueryable<ProviderHardware> ProviderHardwares { get; }
}

// Real DbContext (EF 4.0, Code First)
public class PrimaryDbContext : DbContext, IDbContext
{
   public DbSet<Hardware> Hardwares { get; set; }
   public DbSet<ProviderHardware> ProviderHardwares { get; set; }

   IQueryable<Hardware> IDbContext.Hardwares
     { get { return Hardwares; } }
   IQueryable<ProviderHardware> IDbContext.ProviderHardwares
     { get { return ProviderHardwares; } } 
   ...
}

然后我尝试获取所有硬件,

And i try get all hardwares, which doesnt exists in ProviderHardwares table:

var hardwaresRemoved = db.Hardwares.Where(i => (i.IsAvailable == true) &&
   (db.ProviderHardwares.Count(j => j.Article == i.Article) == 0)).ToList();

如果我严格使用PrimaryDbContext,例如 PrimaryDbContext db = new PrimaryDbContext();一切正常。但是,如果我隐式使用它,则 IDbContext db = new PrimaryDbContext();我得到一个例外:

If i use PrimaryDbContext strictly such as "PrimaryDbContext db = new PrimaryDbContext();" all work fine. But if i use it implicitly "IDbContext db = new PrimaryDbContext();" that i get an exception:


无法创建类型为
的常量值 ConfiguratorMvcApplication.DomainModels.ProviderHardware。在这种情况下,
仅支持
基本类型(例如Int32,String和Guid)。

Unable to create a constant value of type 'ConfiguratorMvcApplication.DomainModels.ProviderHardware'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.



<总结一下,我无法替换IQueryable上的DbSet。在这种情况下,我该如何使用单元测试?我希望有人解决了这个问题...
非常感谢!

Summarize, i can't replace a DbSet on an IQueryable. And how i can use unit testing in this case? I hope someone have resolved this problem yet... Thank in advance very much!

推荐答案

我建议您更好保留DbSet并进行集成测试 包括 数据库。

I suggest you better keep DbSets and do INTEGRATION TESTING including the database.

因为,尽管通过了带有数据库模拟的单元测试可能会有些用,在真实数据库上进行测试会更好(但不是单元测试)。

Because, although passing a unit test with a mock of a DB could be somewhat usefull, you are going to be better off testing with real database (but it's not unit testing).

ClassInitialize擦除数据库和/或创建用于测试的初始数据。

On the ClassInitialize erase the database and/or create the initial data for testing.

如果您创建带有连接字符串的App.config文件,则可以拥有单独的测试数据库,并且如果您使用的是EF Code First,则可以免费获得。

If you create an App.config file with a connection string you can have a separate test database, and if you are using EF Code First, you get it for free.

最诚挚的问候。

这篇关于使用IQueryable&lt; TEntity&gt;而是DbSet&lt; TEntity&gt;问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆