public bool UpdatePost(Post post, List<int> tagIds, string catId) { using (var context = new EFDbContext()) { try { if (post.Id == 0) { var newPost = post; var cats = Categories(); var tags = Tags(); List<Tag> tagsToAdd = (from tagid in tagIds select tags.Find(x => x.Id == tagid)).ToList(); context.Posts.Add(newPost); context.Categories.Attach(cats.Find(m => m.Name.Equals(catId))); newPost.Category = cats.Find(m => m.Name.Equals(catId)); newPost.Tags = new List<Tag>(); foreach (var tagid in tagIds) { Tag t = context.Tags.Find(tagid); newPost.Tags.Add(t); } } else { var postFromDb = context.Posts .Include(p => p.Category) .Include(p => p.Tags) .Single(p => p.Id == post.Id); context.Entry(postFromDb).CurrentValues.SetValues(post); if (post.Category.Id != postFromDb.Category.Id) { context.Categories.Attach(post.Category); postFromDb.Category = post.Category; } postFromDb.Tags.Clear(); foreach (var tagid in tagIds) { Tag t = context.Tags.Find(tagid); postFromDb.Tags.Add(t); } } context.SaveChanges(); return true; } catch (Exception) { return false; } } }
public bool UpdateTag(Tag tag) { using (var context = new EFDbContext()) { try { if (tag.Id == 0) { var newTag = tag; context.Tags.Add(newTag); } else { var tagFromDb = context.Tags .Include(p => p.Posts) .Single(p => p.Id == tag.Id); context.Entry(tagFromDb).CurrentValues.SetValues(tag); } context.SaveChanges(); return true; } catch (Exception) { throw; return false; } } }
public bool UpdateCategory(Category cat) { using (var context = new EFDbContext()) { try { if (cat.Id == 0) { var newCat = cat; context.Categories.Add(newCat); } else { var catFromDb = context.Categories .Include(p => p.Posts) .Single(p => p.Id == cat.Id); context.Entry(catFromDb).CurrentValues.SetValues(cat); } context.SaveChanges(); return true; } catch (Exception) { throw; return false; } } }