Entity Framework - inspect foreach/update query

15,676

Solution 1

ForEach execute and fetch the data from your server. ForEach is not translated into SQL. It just execute the Linq To Entities you just wrote :

var selectQuery = db.Context.SomeTable
    .Where(x => x.abc == someAbc && x.zyx == someZyx);

Which generate the SQL you worte in your question.

Solution 2

As mentioned, ForEach does not get translated into a SQL statement. If you want to make those changes in .NET and save them back to the database, then you'll need to call SaveChanges to update the data source:

var items = db.Context.SomeTable
                      .Where(x => x.abc == someAbc && x.zyx == someZyx);

foreach(var item in items)
{
        item.AuditId = newAuditId;
        item.TimeStamp = newTimestamp;
}

db.Context.SaveChanges();
Share:
15,676
Dimskiy
Author by

Dimskiy

Updated on June 04, 2022

Comments

  • Dimskiy
    Dimskiy almost 2 years

    I have the following query:

    db.Context.SomeTable
        .Where(x => x.abc == someAbc && x.zyx == someZyx)
        .ForEach(y =>
        {
            y.AuditId = newAuditId;
            y.TimeStamp = newTimestamp;
        });
    

    I would like to get the actual SQL query out of the ForEach statement.

    If I do just the following:

    var selectQuery = db.Context.SomeTable
            .Where(x => x.abc == someAbc && x.zyx == someZyx);
    

    I can get the following query from selectQuery variable:

    SELECT 
        [Extent1].[abc] AS [abc], 
        [Extent1].[zyx] AS [zyx] 
        --skipping some [Extent1]. statements for simplicity here
    FROM 
        [dbo].[SomeTable] AS [Extent1]
    WHERE 
        ([Extent1].[abc] = @p__linq__0) AND ([Extent1].[zyx] = @p__linq__1)
    

    Which I can then run outside of Visual Studio, analyze the performance of it, etc.

    How would I do this for the ForEach statement?