private static bool CheckEntityIsAttached <TContext, TEntity>(TContext dbContext, TEntity entity) where TContext : System.Data.Linq.DataContext where TEntity : rsEntityBase { System.Data.Linq.Table <TEntity> entityTbl = dbContext.GetTable <TEntity>(); return(entityTbl.GetOriginalEntityState(entity) != null); }
//*************************************************************************** // Private Methods // private static bool CheckEntityIsAttached <T>(System.Data.Linq.DataContext ctx, T entity) where T : rsEntityBase, new() { // This is *SO* much simpler than the old way I was doing it, it's not even funny. System.Data.Linq.Table <T> entityTbl = ctx.GetTable <T>(); return(entityTbl.GetOriginalEntityState(entity) != null); #region DEPRECIATED - This old method is a cluster, and has been deemed stupid, thanks to me realizing the context will give me the table for a given entity //// NOTE: This is a fairly expensive method call, since it's performing //// two seperate reflection lookups. //// Get the Type of the passed entity. //Type entityType = entity.GetType(); //string entitiyTypeName = entityType.Name; //// Generally, the Linq2Sql table names are the 'plural' form of the entity names. //string srchName = (entitiyTypeName.EndsWith("y") ? entitiyTypeName.TrimEnd('y') + "ies" : entitiyTypeName + "s"); //// Try and find the context's property that the passed entity was queried //// from. This method is *far* from fool-proof. //System.Reflection.PropertyInfo piTableProperty = ctx.GetType().GetProperty(srchName, bindingFlagsPublicInstance); //if (piTableProperty == null) // throw new MemberAccessException(string.Format("Unable to locate property '{0}' in data context.", srchName)); //// If we found the table property, we need to get the value of the property, and //// locate the static 'GetOriginalEntityState' method. //object ctxTable = piTableProperty.GetValue(ctx, null); //Type ctxTableType = ctxTable.GetType(); //System.Reflection.MethodInfo miGetEntityState = ctxTableType.GetMethod("GetOriginalEntityState", new Type[] { entityType }); //if (miGetEntityState == null) // throw new MemberAccessException(string.Format("Unable to locate 'GetOriginalEntityState' method in Type '{0}'.", ctxTableType.Name)); //// If all of that worked out, we just have to call (invoke) the method, and pass //// the supplied entity as a parameter. If we get a 'null' back, then the entity //// is not attached to the context. //object miReturn = miGetEntityState.Invoke(ctxTable, new object[] { entity }); //return miReturn != null; #endregion }