开发者

ASP.NET MVC: No record added to database after POST

[HttpPost]
public开发者_如何学Go 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.


UpdateModel(collection);
context.SaveChanges();

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:

[HttpPost]
public ActionResult Create(Product product)
{
    _repository.Create(product);
    return RedirectToAction("Index", new {controller = "Home"});
}

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.


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.

 context.Customers.Attach(myCustomre);
 context.ObjectStateManager.ChangeObjectState(myCustomre, System.Data.EntityState.Modified);
 context.SaveChanges();

and for insert:

context.Customers.AddObject(newCustomer);
                context.SaveChanges();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜