【发布时间】:2017-12-21 09:43:57
【问题描述】:
首先:我找到了this post,但是我不是很明白,所以请不要把它锁成重复。
我正在尝试使用 ViewModel 进行编辑操作。
我的问题是由于某种原因adds 表的新行而不是editing 它。在我去测试之前,这一切都可以正常工作。
我相信我错过了一些愚蠢的事情,但我不知道我做错了什么。
如果有什么不同,我正在使用code-first
我的视图模型:
public class CreateViewModel
{
public string Title { get; set; }
[Display(Name = "Author")]
public int AuthorId { get; set; }
public DateTime? PublicationDate { get; set; }
public float? Edition { get; set; }
public SelectList Authors { get; set; }
}
我的控制器功能:
// GET: Books/Edit/5
public ViewResult Edit(int? id)
{
if (id == null)
{
return View("Error");
}
Book book = db.Books.FirstOrDefault(a => a.Id == id);
var vm = new CreateViewModel()
{
AuthorId = book.AuthorId,
Authors = new SelectList(db.Authors, "Id", "Name"),
PublicationDate = book.PublicationDate,
Title = book.Title,
Edition = book.Edition
};
if (book == null)
{
return View("Error");
}
return View(vm);
}
// POST: Books/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CreateViewModel vm)
{
if (ModelState.IsValid)
{
var repo = new EFLibraryRepository();
repo.Save(new Book(){
AuthorId = vm.AuthorId,
PublicationDate = vm.PublicationDate,
Title = vm.Title,
Edition = vm.Edition
});
return RedirectToAction("Index");
}
return View("Edit", vm);
}
我的模拟仓库:
public class EFLibraryRepository : ILibraryRepository
{
AuthorAndBookDbModel db = new AuthorAndBookDbModel();
public IQueryable<Author> Authors { get { return db.Authors; } }
public IQueryable<Book> Books { get { return db.Books; } }
public void Delete(Book book)
{
db.Books.Remove(book);
db.SaveChanges();
}
public void Delete(Author author)
{
db.Authors.Remove(author);
db.SaveChanges();
}
public Book Save(Book book)
{
if (book.Id == 0)
{
db.Books.Add(book);
}
else
{
db.Entry(book).State = System.Data.Entity.EntityState.Modified;
}
db.SaveChanges();
return book;
}
public Author Save(Author author)
{
if (author.Id == 0)
{
db.Authors.Add(author);
}
else
{
db.Entry(author).State = System.Data.Entity.EntityState.Modified;
}
db.SaveChanges();
return author;
}
}
ILibraryRepository:
public interface ILibraryRepository
{
IQueryable<Book> Books { get; }
IQueryable<Author> Authors { get; }
Book Save(Book book);
Author Save(Author author);
void Delete(Book book);
void Delete(Author author);
}
【问题讨论】:
-
你的视图模型没有
Id属性,当你保存Book时,你没有设置它的Id属性,所以它总是0你总是叫@ 987654333@ -
但无论如何你的设计都是错误的。您应该基于
Id从数据库中获取原始数据模型(只需将public int? Id { get; set }属性添加到您的视图模型,使其自动绑定),然后您从视图模型更新其属性。 -
OK 现在完美运行。你想添加一个答案,以便我选择最好的吗?
-
把它放在这里,我明天去取。感谢您的帮助!
-
当你在虚拟机中获取编辑方法的信息时,也只需获取书籍的 id,然后从数据库中获取书籍对象,编辑它,将其标记为
EntityState.Modified,然后保存它.它肯定会起作用。
标签: c# asp.net asp.net-mvc unit-testing