Is there a way to UPDATE data and SELECT updated ids on output in the same query using entity framework core?

.net entity-framework entity-framework-core


I'd like to update a set of rows based on a simple linq criteria and return updated ids. I know how to do it with raw sql using OUTPUT statement, but I don't want to mix raw sql code with linq statements.Is there a way to do this by linq?


UPDATE Foo SET Bar = 1 OUTPUT INSERTED.Id WHERE createDate not null

8/27/2018 7:44:08 PM

Popular Answer

I'm not really sure about the differences between ef-core with full entity framework.

In entity framework none of your changes is actually saved in the database until you call SaveChanges. If you assert that you are the only user of your dbContext object, you can ask this dbContext object for collections of the objects that will be inserted and updated when you call SaveChanges.

As no one else is using your dbContext object, you can be sure that between asking for these collections and the actual SaveChanges nothing changes:

using (var dbContext =  new MyDbContext(...))
    // Insert and Change some items

    // ask the DbContext which items are Inserted / Changed
    var changeTracker = dbContext.ChangeTracker;

    // get all inserted items:
    var allInsertedItems = changeTracker.Entries()
        .Where(entry => entry.State == EntityState.Added);

    // or get the original and changed value of changed Contracts:
    var allChangedContracts = changeTracker.Entries<Contract>()
        .Where(contact => contract.State == Enitystate.Modified)
        .Select(contract => new
            OriginalValue = contract.OriginalValue,
            ChangedValue = contract.Value,

    // when ready to save the changes:
8/28/2018 8:31:54 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow