/// <summary> /// 附加对象到上下文;如果已经有此实体对象,则不会进行 Attach 操作; /// </summary> public void SafeAttach(Type entityType, IId entity) { if (!this.ChangeTracker.Entries().Any(a => DbContextUtil.GetEntityType(a.Entity.GetType()) == entityType && ((IId)a.Entity).Id == entity.Id)) { #if NETCOREAPP2_2 this.Attach(entity); #else this.Set(entityType).Attach(entity); #endif // this.Set(entityType).Attach(entity); // } }
/// <summary> /// 维护实体 UpperIds 字段; /// </summary> /// <param name="context"></param> /// <param name="entityType"></param> /// <param name="state"></param> /// <param name="entity"></param> public static void MaintainUpperids(DbContext context, Type entityType, EntityState state, object entity) { entityType = DbContextUtil.GetEntityType(entityType); if (!typeof(IdEntity).IsAssignableFrom(entityType) || !typeof(IRelateToUpper).IsAssignableFrom(entityType)) { throw new Exception(entityType.Name + " 未实现 IId 和 IRelateToUpper 接口,不可以调用此方法"); } MethodInfo methodInfo = null; if (!typeGenericMethodMap.TryGetValue(entityType, out methodInfo)) { methodInfo = GenericMaintainUpperidsWhenCreate = typeof(IRelateToUpperUtil) .GetMethods(BindingFlags.Static | BindingFlags.Public) .First(a => a.Name == "MaintainUpperids" && a.IsGenericMethod) .MakeGenericMethod(new Type[] { entityType }); typeGenericMethodMap[entityType] = methodInfo; } // GenericMaintainUpperidsWhenCreate.Invoke(null, new object[] { context, state, entity }); 每个类型都会定义不同的泛型方法中; methodInfo.Invoke(null, new object[] { context, state, entity }); }