需要一个集中式解决方案,以便将结果Entity
保留为Db,可能位于SaveChangesAsync()
的{{1}}和SaveChanges()
方法内,或者通过事件监听器。
需要生成的实体值才能包含所有新的DbContext
属性。即。.ValueGeneratedOnAdd[Updated/etc]()
,RowVersion
等。
目的是传达Updated
之前和之后的并发通信。
这就是我到目前为止:第一种方法会产生额外的,不必要的Db命中。
Entity
此外,我已订阅github问题EntityFrameworkCore - Lifecycle hooks #626上提及或链接的新状态更改事件 public override async Task<int> SaveChangesAsync(
CancellationToken cancellationToken = new CancellationToken() )
{
var before = ChangeTracker.Entries().AsEnumerable().First();
var res = await base.SaveChangesAsync(cancellationToken);
/* ********************************************************
I can do the following, but this results in an extra
DbQuery. I know that if this were a consumer
method with entity, after I called SaveChangesAsync() it
would have the new resulting values. Just not sure how
to access here inside SaveChangesAsync()?
********************************************************** */
await ChangeTracker.Entries().AsEnumerable().First().ReloadAsync();
/* ********************************************************
^ Additionally, ReloadAsync has a "Note, however, that an
Added entity may not yet have had its permanent key value
created.
********************************************************** */
var after = ChangeTracker.Entries().AsEnumerable().First();
return res;
}
和Tracked
:
对于Ex:
StateChagned
然而,public class StateListener : IEntityStateListener
{
public void StateChanging(InternalEntityEntry entry, EntityState newState)
{
Console.WriteLine(
" Changing {0} from {1} to {2}.",
entry.Entity.GetType().Name, entry.EntityState, newState);
}
public void StateChanged(InternalEntityEntry entry,
EntityState oldState, bool fromQuery)
{
Console.WriteLine(
" Changed {0} to {1} from {2}.",
entry.Entity.GetType().Name, entry.EntityState, oldState);
}
public void StateChanged(InternalEntityEntry entry, EntityState oldState,
bool skipInitialFixup, bool fromQuery)
{
Console.WriteLine(
" Changed {0} from {1} to {2}.",
entry.Entity.GetType().Name, oldState, entry.EntityState);
}
}
中的newState
和InternalEntityEntry
都拥有应该保存的值,而不是Db设置的新值,例如StateChanged
,{ {1}}等等。
答案 0 :(得分:1)
为那些搜索类似的人提供答案 - 在提出这个问题时,我有一个基本的误解。我相信一个持有Db的实体会在SaveChanges[Async]()
更新其所有值。我相信这是因为这是主键的行为,如&#34; How can I get Id of inserted entity in Entity framework?&#34;
对于.ValueGeneratedOnAdd[Updated/etc]()
且不是RowVersion或PrimaryKeys的属性,情况并非如此。
根据这种理解,任何可能的解决方案都可能需要查询Db。我考虑过向OnCommandExecuting
添加此类查询,然后使用OnCommandExecuted
中的结果,但由于其性质而被放弃。