如何在数据库中编辑我的记录

时间:2018-04-21 16:55:44

标签: asp.net-mvc

我正在尝试在db中编辑我的记录但不知何故我只是添加了另一条记录。我需要在代码中更改什么内容?

我尝试编写db.NewsPortals.Update(image);而不是db.NewsPortals.Add(image);,但Visual Studio无法识别。为什么呢?

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(int id, NewsPortalViewModel model)
    {
        var validImageTypes = new string[]
        {
         "image/gif",
         "image/jpeg",
         "image/pjpeg",
         "image/png"
        };

        if (ModelState.IsValid)
        {
            var image = db.NewsPortals.Find(id);

            if (image == null)
            {
                return new HttpNotFoundResult();
            }

            image.Id = model.Id;
            image.Title = model.Title;
            image.Description = model.Description;

            if (model.ImageFile != null && model.ImageFile.ContentLength > 0)
            {
                var uploadDir = "~/Image";
                var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageFile.FileName);
                var imageUrl = model.ImageFile.FileName;
                model.ImageFile.SaveAs(imagePath);
                image.ImageUrl = imageUrl;
            }

            db.NewsPortals.Add(image);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(model);
    }

1 个答案:

答案 0 :(得分:0)

如果删除此行,则应该有效。

db.NewsPortals.Add(image);