Moq实体框架ExecuteSQLCommand [英] Moq Entity Frameworks ExecuteSQLCommand

查看:77
本文介绍了Moq实体框架ExecuteSQLCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到,使用最小起订量时,您不能模拟非虚函数.我还读到现在应该可以做到这一点. 如果是这样,那么我想模拟以下查询:

I've read that when using moq you cannot mock a non-virtual function. I've also read that this should be possible now.. Is that true? If so, then I'd like to mock the following query:

DatabaseContext.Database.ExecuteSqlCommand(updateQuery, newValue);

我正在测试中覆盖Context

I'm overriding the Context in my test as so

DAL.Context.DatabaseContext = mockContext.Object;

我已经尝试过这种设置,但是查询仍然消失了,而不是我的常规数据库

I've tried this setup, but it seems the query stills goes agains my regular db

mockContext.Setup(c => c.Set<AppSalesAndResult>()).Returns(mockBudgetData.Object);

任何想法,也许可以将executesql命令替换为其他内容,以使上面的行捕获到该集合的所有udpate吗?由于性能原因,我在一次更新多行时使用executesqlcommand.常规EF太慢

Any ideas, could perhaps the executesqlcommand be replaced with something else so that the row above would catch any udpates to the set? I use executesqlcommand due to performance reasons when updating multiple rows at once. Regular EF is too slow

更新:

阅读以下帖子,如何进行Moq实体框架SqlQuery调用我想知道类似的实现是否对ExecuteSQLCommand有用...

Reading the following post, How to Moq Entity Framework SqlQuery calls I wonder if a similar implementation would work for ExecuteSQLCommand...

推荐答案

我想对ExecuteSqlCommand进行模拟,这是在DataBase类中无法做到的,它是在我的DbContext继承中创建相同的方法,但这进行虚拟操作,然后调用Database.ExecuteSqlCommand

What I have done to being able to Mock ExecuteSqlCommand, which is not possible to do in DataBase class, was to create the same method in my DbContext inheritance but this time virtual, and call the Database.ExecuteSqlCommand

public class MyDbContext : DbContext
{
    public virtual int ExecuteSqlCommand(string sql, params object[] parameters)
    {
        return Database.ExecuteSqlCommand(sql, parameters);
    }
    public virtual int ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, string sql, params object[] parameters)
    {
        return Database.ExecuteSqlCommand(transactionalBehavior, sql, parameters);
    }

然后,我更改了业务代码以调用此创建的方法(非数据库方法):

Then I changed my business code to call this created method (Not Database method):

DatabaseContext.ExecuteSqlCommand(updateQuery, newValue);

然后,它起作用

这篇关于Moq实体框架ExecuteSQLCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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