示例#1
0
        public ActionResult Create(Blog blog)
        {
            blog.Metadata.CreatedOn = DateTime.Now;
            blog.Metadata.LastUpdated = DateTime.Now;
            blog.Metadata.Blog = blog;
            //db.BlogMetadatas.Add(blog.Metadata);
            //var metadata = blog.Metadata;
            //blog.Metadata = null;

            db.Blogs.Add(blog);
            //blog.Metadata = new BlogMetadata();

            try
            {

                /* //method 2
                var errors=db.GetValidationErrors();
                if (errors.Count() > 0)
                {
                    HandleValidationResult(errors);
                    return View(blog);
                }
                */
                /*
                //method 3
                var validationResult = db.Entry(blog).GetValidationResult();
                if (!validationResult.IsValid && validationResult.ValidationErrors.Count() > 0)
                {
                    HandleValidationResult(new List<DbEntityValidationResult> { validationResult });
                    return View(blog);
                }
                */
                //method 4

                var validationResults = db.Entry(blog).Property(m => m.Title).GetValidationErrors();
                if (validationResults.Count() > 0)
                {
                    foreach (var error in validationResults)
                    {
                        ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                    }

                    return View(blog);
                }

                db.SaveChanges();
            }
            catch
            {
                throw;
            }
            /* //method 1
            //catch (DbEntityValidationException ex)
            //{
            //    HandleValidationResult(ex.EntityValidationErrors);

            //    return View(blog);
            //}
            */
            //metadata.BlogId = blog.Id;
            //metadata.Blog = blog;

               // db.BlogMetadatas.Add(metadata);
               // db.SaveChanges();

            return RedirectToAction("Edit", new { id = blog.Id });
        }
示例#2
0
        public ActionResult Edit(Blog blog)
        {
            if (ModelState.IsValid)
            {
                var originalBlog = db.Blogs.Include(m=>m.Metadata).FirstOrDefault(m => m.Id == blog.Id);
                originalBlog.Title = blog.Title;
                originalBlog.CreatedBy = blog.CreatedBy;
                originalBlog.Metadata.Language = blog.Metadata.Language;
                originalBlog.Metadata.LastUpdated = DateTime.Now;

                db.SaveChanges();
                return RedirectToAction("Index");

            }

            return View(blog);
        }