public static void LoadCollection <TEntity, TCollection>( this IDbContext ctx, TEntity entity, Expression <Func <TEntity, ICollection <TCollection> > > navigationProperty, bool force = false, Func <IQueryable <TCollection>, IQueryable <TCollection> > queryAction = null) where TEntity : BaseEntity where TCollection : BaseEntity { Guard.NotNull(entity, nameof(entity)); Guard.NotNull(navigationProperty, nameof(navigationProperty)); var dbContext = ctx as DbContext; if (dbContext == null) { throw new NotSupportedException("The IDbContext instance does not inherit from DbContext (EF)"); } var entry = dbContext.Entry(entity); var collection = entry.Collection(navigationProperty); // Avoid System.InvalidOperationException: Member 'IsLoaded' cannot be called for property... if (entry.State == System.Data.Entity.EntityState.Detached) { ctx.Attach(entity); } if (force) { collection.IsLoaded = false; } if (!collection.IsLoaded) { if (queryAction != null || ctx.ForceNoTracking) { var query = !ctx.ForceNoTracking ? collection.Query() : collection.Query().AsNoTracking(); var myQuery = queryAction != null ? queryAction(query) : query; collection.CurrentValue = myQuery.ToList(); } else { collection.Load(); } collection.IsLoaded = true; } }
public ActionResult Edit(Review review) { if (ModelState.IsValid) { //review.Body = Sanitizer.GetSafeHtmlFragment(review.Body); _db.Attach(review); _db.SaveChanges(); return(RedirectToAction("Index")); } return(View(review)); }
public static void AttachRange <TEntity>(this IDbContext ctx, IEnumerable <TEntity> entities) where TEntity : BaseEntity { entities.Each(x => ctx.Attach(x)); }
/// <summary> /// Attaches the entity to the underlying context of this reposity. /// It is placed in the Unchanged state as if it was just read from the database /// </summary> /// <param name="entity">The entity to attach</param> /// <param name="markDirty">Marks the newly attached entity as modified</param> /// <returns></returns> public void Attach(T entity, bool markDirty = false) { _context.Attach(entity, markDirty); }