是在ASP.NET MVC中更新数据的好方法吗?

时间:2019-07-11 19:54:40

标签: asp.net-mvc entity-framework linq

我正在更新数据库中的现有数据。基本上,我从表中检索所有数据,然后一个接一个地手动更新每一列。您认为这是个好方法吗?或者,请建议我另一种简单的方法。我的方法看起来很长,我的意思是要更新很多行。

[HttpPost]
public ActionResult SaveMovie(HttpPostedFileBase file, MovieViewModel model)
{
        if (!ModelState.IsValid)
        {
            var viewModel = new MovieViewModel
            {
                ProHouses = _context.ProHouses.ToList()
            };

            return View("AddMovie", viewModel);
        }

        if (model.Movies.Id == 0)
        {
            if (file != null)
            {
                Guid RandomName = Guid.NewGuid();
                var fileExtention = Path.GetExtension(file.FileName);
                var FileName = RandomName + fileExtention;
                var path = Path.Combine(Server.MapPath("~/MovieTitle"), RandomName + fileExtention);
                file.SaveAs(path);
                model.Movies.TitleURL = FileName;
            }

            _context.Movies.Add(model.Movies);
        }
        else
        {
            var movieInTable = _context.Movies.SingleOrDefault(m => m.Id == model.Movies.Id);
            movieInTable.Budget = model.Movies.Budget;
            movieInTable.Writer = model.Movies.Writer;
            movieInTable.Country = model.Movies.Country;
            movieInTable.Genre = model.Movies.Genre;
            movieInTable.Duration = model.Movies.Duration;
            movieInTable.Plot = model.Movies.Plot;
            movieInTable.Name = model.Movies.Name;
            movieInTable.ProHouseId = model.Movies.ProHouseId;
            movieInTable.Rating = model.Movies.Rating;
            movieInTable.Director = model.Movies.Director;
            movieInTable.Year = model.Movies.Year;
            movieInTable.TitleURL = model.Movies.TitleURL;
        }

        _context.SaveChanges();

        ViewBag.Message = "Movie Added";

        return View("Confirmation");
}

我对这部分感到困惑

else
{
    var movieInTable = _context.Movies.SingleOrDefault(m => m.Id == model.Movies.Id);
    movieInTable.Budget = model.Movies.Budget;
    movieInTable.Writer = model.Movies.Writer;
    movieInTable.Country = model.Movies.Country;
    movieInTable.Genre = model.Movies.Genre;
    movieInTable.Duration = model.Movies.Duration;
    movieInTable.Plot = model.Movies.Plot;
    movieInTable.Name = model.Movies.Name;
    movieInTable.ProHouseId = model.Movies.ProHouseId;
    movieInTable.Rating = model.Movies.Rating;
    movieInTable.Director = model.Movies.Director;
    movieInTable.Year = model.Movies.Year;
    movieInTable.TitleURL = model.Movies.TitleURL;
}

1 个答案:

答案 0 :(得分:2)

首先,编写的代码很难重用,并且在维护过程中会遇到困难。假设您正在重复这样的代码并在多个文件中使用它,突然发现您需要另一个字段并且需要添加该字段。因此,您必须更改所有代码。

第二,建议不要将数据操作代码放在控制器中。尝试创建另一个层(类项目)以放置此类代码。结合使用Automapper类库绝对可以帮助您减少映射。

否则,正如Travis上面建议的那样,您可以使用构造函数来填充属性。