简体   繁体   English

来自EF7 Database.SqlQuery的字符串循环列表

[英]Looping list of strings from EF7 Database.SqlQuery

I am wanting to run some tests on a new API we have. 我想对我们拥有的新API进行一些测试。 So I want to load about 115 VINs from the db and plug them into the API call. 因此,我想从数据库中加载大约115个VIN,并将其插入API调用中。 I know using a model is best practice but just for the sake of testing I would prefer to not have to build a model every time I simply want to test something like this and then have to delete the model and remove it from the context later. 我知道使用模型是最佳实践,但是仅出于测试目的,我宁愿不必每次都只想测试类似的东西时就构建模型,然后再删除模型并将其从上下文中删除。

I simply want to get a list of VIN strings which I can loop through somehow. 我只是想获得一个VIN字符串列表,我可以通过某种方式循环浏览。

Here is my code: 这是我的代码:

dynamic ret = new ExpandoObject();

ret.vehicles = _context.Database.SqlQuery<string>("SELECT MIN(VIN) FROM bl_DealerInventory WHERE DealerID = "+ dealer.ClientDealerID +" GROUP BY Year, Make, Model, ModelNumber");

for (var i = 0; i < ret.vehicles.Count; i++)
{
    System.Diagnostics.Debug.WriteLine("Ran vin "+ ret.vehicles[i]);
}

The SQL works but I can't seem to find a way to change it to a list so I can loop through it. SQL有效,但是我似乎找不到找到将其更改为列表的方法,因此可以循环遍历它。 How can I loop through it? 我如何遍历它? Or do I have to cast it as something else or what? 还是我必须将其转换为其他或其他内容?

Here is the Entity framework I am using: 这是我正在使用的实体框架:

<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net461" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net461" />

Let me know if there is any other information needed. 让我知道是否需要其他信息。 Thank you. 谢谢。

I got the loop working using a foreach instead of a for loop. 我使用foreach而不是for循环来使循环工作。

The reason for this as stated by Pawel Hemperek: 如Pawel Hemperek所述,其原因如下:

Because SqlQuery returns DbRawSqlQuery which implements IEnumerable and executes query when enumerated. 因为SqlQuery返回DbRawSqlQuery,它实现IEnumerable并在枚举时执行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM