gpt4 book ai didi

c#-4.0 - 使用 IQueryable 代替 DbSet 问题

转载 作者:行者123 更新时间:2023-12-04 16:12:49 26 4
gpt4 key购买 nike

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

// 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; } }
...
}

我尝试获取 ProviderHardwares 表中不存在的所有硬件:

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();”我得到一个异常(exception):

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。在这种情况下我如何使用单元测试?我希望有人已经解决了这个问题......
非常感谢!

最佳答案

我最终为每个 DbSet 提供了两个属性:一个是 IQueryable 类型,一个是 DbSet 类型。 IQueryable 属性在接口(interface)中定义,它将调用中继到具体实现(DbSet 类型的属性),如下所示:

// Exists in the interface
public IQueryable<AccountContact> AccountContacts
{
get
{
return DbAccountContacts;
}
set
{
DbAccountContacts = (DbSet<AccountContact>)value;
}
}

// Exists only in the implementation
public DbSet<AccountContact> DbAccountContacts { get; set; }

有了这个设置,我就可以让 mocking 正常工作,并且可以对代码进行单元测试。

这对于 OP 来说绝对为时已晚,但也许这可以帮助像我一样在同一个问题上苦苦挣扎的人。

关于c#-4.0 - 使用 IQueryable<TEntity> 代替 DbSet<TEntity> 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7139352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com