ASP.net MVC3如何编辑sql数据库

时间:2012-09-11 09:32:18

标签: c# sql asp.net-mvc-3 linq

MovieStoreEntities MovieDb = new MovieStoreEntities();
public ActionResult Edit(int id)
{

    //var EditMovie1 = MovieDb
    AddMovieModel EditMovie = (from M in MovieDb.Movies
                               from C in MovieDb.Categories
                               where M.CategoryId == C.Id
                               where M.Id == id
                               select new AddMovieModel { Name = M.Name, Director = M.Director, Country = M.Country, categorie = C.CategoryName, Category = M.CategoryId }).FirstOrDefault();

    //AddMovieModel EditMovie1 = MovieDb.Movies.Where(m => m.Id == id).Select(m => new AddMovieModel {m.Id   }).First();
    List<CategoryModel> categories = MovieDb.Categories
       .Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id })
       .ToList();

    ViewBag.Category = new SelectList(categories, "Id", "Category");


    return View(EditMovie);
}

//
// POST: /Default1/Edit/5

[HttpPost]
public ActionResult Edit(AddMovieModel Model2)
{
    List<CategoryModel> categories = MovieDb.Categories
        .Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id })
        .ToList();
    ViewBag.Category = new SelectList(categories, "Id", "Category");



    if (ModelState.IsValid)
    {
        //MovieStoreEntities model = new MovieStoreEntities();






        MovieDb.SaveChanges();


        return View("Thanks2", Model2);
    }
    else
        return View();

}

这是我编写的用于在sql server中编辑Movie详细信息和更新数据库的代码。 这没有任何编译错误,但它没有更新sql server数据库。

2 个答案:

答案 0 :(得分:4)

假设您正在更新您需要执行类似

的类别
 List<CategoryModel> categories = MovieDb.Categories
    .Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id })
    .ToList();
ViewBag.Category = new SelectList(categories, "Id", "Category")
Category category = new Category()
category = categories.First(p=>p.CategoryId == Id);
category.Name = "New Name";
MovieDb.Categories.SaveChanges(category);
MovieDb.SaveChanges();

您需要获取您想要编辑的项目...在这种情况下,将从类别列表中过滤出一个类别。然后,您可以在该实体上调用savechanges方法,即MovieDb.Categories.SaveChanges(),并传递您要更新的项目。

答案 1 :(得分:0)

您需要使用Model2对象创建新实体,将其添加到ObjectContext并保存更改。您还没有编写任何应该将任何内容保存到数据库的代码。