ASP.NET MVC:POST 后没有记录添加到数据库
[HttpPost]
public ActionResult Create(FormCollection collection)
{
UpdateModel(collection);
context.SaveChanges();
return RedirectToAction("Index", new {controller = "Home"});
}
操作成功,但没有记录插入到数据库中。为什么?
我不想通过从表单集合中的每个字段获取每个值来手动创建对象。
[HttpPost]
public ActionResult Create(FormCollection collection)
{
UpdateModel(collection);
context.SaveChanges();
return RedirectToAction("Index", new {controller = "Home"});
}
The action succeed, but there was no recored inserted into the database. Why?
I do not want to manually create a object by getting each value from each field in form collection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有对上下文进行任何更改以期望保存某些内容。实体框架(假设这就是您正在使用的)与对象一起使用。所以你需要一个模型并将这个模型持久化到数据库中。因此,您的控制器操作可能如下所示:
其中
_repository
变量是定义模型操作的某个接口。此处使用接口允许您将数据访问逻辑与控制器逻辑分开。在此存储库的实现中,您可以使用任何您喜欢的数据访问技术,例如 EF 或 NHibernate,只是您的控制器不应该知道它。You didn't made any changes to the context in order to expect something to get saved. Entity Framework (assuming this is what you are using) works with objects. So you need a model and persist this model into the database. So your controller action could look like this:
where the
_repository
variable is some interface which defines the operations on your models. Using an interface here allows you to separate your data access logic from your controller logic. In the implementation of this repository you could be using any data access technology you like such as EF or NHibernate, it's just that your controller shouldn't know about it.您确定上下文是打开的并且与从中提取对象的上下文相同吗?该对象仍然连接到上下文吗?
通常,您在每次调用中创建一个新上下文,您需要将对象附加到上下文,将其状态更改为已修改,然后使用 SaveChanges。
否则,什么也不做。
对于插入:
Are you sure the context is open and it's the same from which your object has been extracted ? is the object is still connected to the context ?
usually you create a new context in each call, you need to attach the object to the context change it state to modified and than use SaveChanges.
Otherwise, nothing is done.
and for insert: