示例#1
0
        public void EditNote(int id, NoteWithCategories newNote)
        {
            var oldNote = _context.Notes.Where(n => n.NoteID == id &&
                                               n.Timestamp == newNote.Timestamp).FirstOrDefault();

            if (oldNote == null)
            {
                throw new Exception("The file does not exist or has been changed");
            }
            // Find differences in standard fields and replace if needed
            if (oldNote.Title != newNote.Title ||
                oldNote.Description != newNote.Description ||
                oldNote.NoteDate != newNote.NoteDate ||
                oldNote.IsMarkdown != newNote.IsMarkdown)
            {
                oldNote.Title       = newNote.Title;
                oldNote.Description = newNote.Description;
                oldNote.NoteDate    = newNote.NoteDate;
                oldNote.IsMarkdown  = newNote.IsMarkdown;
            }

            // Find differences in categories

            var categoriesInDb = _context.NoteCategories
                                 .Where(nc => nc.Note == oldNote)
                                 .Include(nc => nc.Category);

            var newCategories = newNote.Categories
                                .Except(categoriesInDb.Select(c => c.Category.Title));

            foreach (var newCategory in newCategories)
            {
                var categoryInDb = _context.Categories
                                   .Where(c => c.Title == newCategory)
                                   .FirstOrDefault();

                if (categoryInDb == null)
                {
                    categoryInDb = new Category
                    {
                        Title = newCategory
                    };
                }
                _context.Add(new NoteCategory
                {
                    Note     = oldNote,
                    Category = categoryInDb
                });
            }

            var deletedCategories = categoriesInDb
                                    .Where(c => !newNote.Categories.Contains(c.Category.Title));

            _context.RemoveRange(deletedCategories);
            _context.SaveChanges();
        }