我一直在嘗試實現一種解決方案,以在斷開連接的情況下正確設置實體上的狀態(在這種情況下,每次調用 NetCore API 都會加載 DBContext 的新實例)。Julie Lehrmann 的 Book Programming Entity Framework 中有一個解決方案,它提出了一個我想要實現的解決方案。不幸的是,它是為 EF 6 編寫的。如何為 EF Core 編寫這些方法?public BreakAwayContext(){ ((IObjectContextAdapter)this).ObjectContext .ObjectMaterialized += (sender, args) => { var entity = args.Entity as IObjectWithState; if (entity != null) { entity.State = State.Unchanged; entity.OriginalValues = BuildOriginalValues(this.Entry(entity).OriginalValues); } };}private static Dictionary<string, object> BuildOriginalValues( DbPropertyValues originalValues){ var result = new Dictionary<string, object>(); foreach (var propertyName in originalValues.PropertyNames) { var value = originalValues[propertyName]; if (value is DbPropertyValues) { result[propertyName] = BuildOriginalValues((DbPropertyValues)value); } else { result[propertyName] = value; } } return result;}最后這個方法private static void ApplyChanges<TEntity>(TEntity root) where TEntity : class, IObjectWithState{ using (var context = new BreakAwayContext()) { context.Set<TEntity>().Add(root); CheckForEntitiesWithoutStateInterface(context); foreach (var entry in context.ChangeTracker .Entries<IObjectWithState>()) { IObjectWithState stateInfo = entry.Entity; entry.State = ConvertState(stateInfo.State); if (stateInfo.State == State.Unchanged) { ApplyPropertyChanges(entry.OriginalValues, stateInfo.OriginalValues); } } context.SaveChanges(); }}非常感謝您幫助我將其翻譯成 EF Core 兼容代碼!原始代碼可以在這里找到 https://www.oreilly.com/library/view/programming-entity-framework/9781449331825/ch04.html
1 回答

蝴蝶不菲
TA貢獻1810條經驗 獲得超4個贊
您很快將不再需要將它們遷移到 EF Core,因為EF 6.3 將以 .NET Standard 2.1 為目標。
要使用它,您需要將項目遷移到 .NET Core 3.0 或 .NET Standard 2.1 for libraries。
.NET Core 3.0 將在今年下半年發布,或者你可以像現在一樣使用預覽版 SDK 冒一點風險。
- 1 回答
- 0 關注
- 134 瀏覽
添加回答
舉報
0/150
提交
取消