public static IQueryable <T> OrderByField <T>(this IQueryable <T> source, string fieldName) { PropertyInfo pi = typeof(T).GetProperty(fieldName); var mInfo = typeof(Queryable).GetMethods().Where(mi => mi.Name == "OrderBy" && mi.GetParameters().Length == 2).Single(); var mInfoGen = mInfo.MakeGenericMethod(typeof(T), pi.PropertyType); return((IQueryable <T>)mInfoGen.Invoke(null, new object[] { source, LinqX.GetFieldSelector <T>(fieldName) })); }
/// <summary> /// Update an entity in a context, taking appropriate action based on /// whether it is already tracked or not /// </summary> /// <param name="context">The database context</param> /// <param name="entity">The entity to update in the context</param> public static void SafeUpdate(this DbContext context, object entity) { var entry = context.Entry(entity); if (entry.State != EntityState.Detached) { return; } Type entityType = entity.GetType().ContentType(); object id = LinqX.GetIdProp(entity.GetType(), null).GetValue(entity); var attachedEntity = context.Set(entityType).Find(id); if (attachedEntity != null) { context.Entry(attachedEntity).CurrentValues.SetValues(entity); } else { entry.State = EntityState.Modified; } }