public bool CreatePost(Post newPost) { try { using (var context = new EFDbContext()) { context.Posts.Add(newPost); context.SaveChanges(); return true; } } catch (Exception) { return false; } }
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; } } }