简体   繁体   中英

Looping list of strings from EF7 Database.SqlQuery

I am wanting to run some tests on a new API we have. So I want to load about 115 VINs from the db and plug them into the API call. 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.

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. 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.

The reason for this as stated by Pawel Hemperek:

Because SqlQuery returns DbRawSqlQuery which implements IEnumerable and executes query when enumerated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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