gpt4 book ai didi

C#:测试 Entity Framework FromSql 以确保语法正确

转载 作者:行者123 更新时间:2023-12-04 02:34:29 25 4
gpt4 key购买 nike

我写信是为了用 InMemory 数据库测试 FromSql 语句。我们正在尝试使用 Sqlite。

运行下面的Sql通过单元测试没有报错。

select * from dbo.Product

但是,这样做也会通过不正确的 sql 语法。想用不正确的 sql 语法使测试失败。我们如何正确测试 FromSql?

没有错误来自语法错误的结果。

seledg24g5ct * frofhm dbo.Product

完整代码:

namespace Tests.Services
{
public class ProductTest
{
private const string InMemoryConnectionString = "DataSource=:memory:";
private SqliteConnection _connection;
protected TestContext testContext;

public ProductServiceTest()
{
_connection = new SqliteConnection(InMemoryConnectionString);
_connection.Open();
var options = new DbContextOptionsBuilder<TestContext>()
.UseSqlite(_connection)
.Options;
testContext= new TestContext(options);
testContext.Database.EnsureCreated();
}


[Fact]
public async Task GetProductByIdShouldReturnResult()
{
var productList = testContext.Product
.FromSql($"seledg24g5ct * frofhm dbo.Product");

Assert.Equal(1, 1);
}

使用网络核心 3.1

最佳答案

这里有两件事需要考虑。

首先,FromSql方法只是在 EF Core 中使用原始 SQL 查询的一个小桥梁。当调用该方法时,除了查找参数占位符并将数据库参数与它们相关联之外,不会对传递的 SQL 字符串进行任何验证/解析。为了得到验证,它必须被执行

其次,为了支持对 FromSql 的查询组合结果集,方法返回IQueryable<T> .这意味着它不会立即执行,而是仅当/当枚举结果时才执行。当您使用 foreach 时可能会发生这种情况遍历它,或调用类似 ToList 的方法, ToArray或 EF Core 特定 Load扩展方法,类似ToList , 但不创建列表 - 相当于 foreach没有主体的循环,例如

foreach (var _ in query) { }

话虽如此,代码片段

var productList = testContext.Product
.FromSql($"seledg24g5ct * frofhm dbo.Product");

基本上什么都不做,因此不会为无效 SQL 产生异常。您必须使用上述方法之一执行它,例如

productList.Load();

var productList = testContext.Product
.FromSql($"seledg24g5ct * frofhm dbo.Product")
.ToList();

并断言预期的异常。

有关详细信息,请参阅 Raw SQL QueriesHow Queries Work EF Core 文档的部分。

关于C#:测试 Entity Framework FromSql 以确保语法正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62482710/

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