简体   繁体   English

EF 更改跟踪器和存储过程

[英]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.我的 model 使用的是数据库优先的方法,其中不导入存储过程,只存在于数据库中。

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 .我需要通过ExecuteSqlCommand执行我的存储过程,我想跟踪这些更改,但不幸的是,通过执行存储过程(插入、删除)修改的实体未在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.下一个想法是强制我的实体通过 linq 查询未修改的 state 进入更改跟踪器,然后运行存储过程,但它似乎没有被跟踪。

I'm out of ideas.我没主意了。 This is required to rollback changes done by stored procedures after test finish.这是在测试完成后回滚存储过程所做的更改所必需的。

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

Creates a raw SQL query that will return elements of the given generic type.创建一个原始的 SQL 查询,它将返回给定泛型类型的元素。 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.即使返回的 object 类型是实体类型,上下文也永远不会跟踪此查询的结果。

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

Creates a raw SQL query that will return entities in this set.创建一个原始的 SQL 查询,它将返回该集合中的实体。 By default, the entities returned are tracked by the context;默认情况下,返回的实体由上下文跟踪;

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

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