简体   繁体   中英

EF change tracker and stored procedures

My model is using a database-first approach where stored procedures are not imported and exist only in the database.

I need to execute my stored procedures via ExecuteSqlCommand and I would like to track those changes, but unfortunately entities modified by executing stored procedures (insert, delete) are not listed in ChangeTracker().Entries .

I've tried:

context.Database.BeginTransaction();

var result = context.Database.ExecuteSqlCommand(storedProcedureName, parameters);

var trackedEntities = context.ChangeTracker
                             .Entries()
                             .Where(x => x.State != EntityState.Unchanged)
                             .ToList();

context.Database.CurrentTransaction.Commit();

I've also tried to dig in current transaction but actually there is nothing that I could use. Next idea was to force my Entity to get in change tracker with state unmodified with querying it via linq and than run stored procedure but it seems it's not tracked ad all.

I'm out of ideas. This is required to rollback changes done by stored procedures after test finish.

Try Database.SqlQuery<TElement>(String, Object[]) :

Creates a raw SQL query that will return elements of the given generic type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.

Or DbSet<TEntity>.SqlQuery(String, Object[]) :

Creates a raw SQL query that will return entities in this set. By default, the entities returned are tracked by the context;

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