Reputation: 671
I'm fairly new to MVC so please be patient. Here's my action code in my controller in an MVC project I'm working on:
[HttpPost]
public ActionResult Create(User usr , string submitBtn, FormCollection form, int id)
{
var db = new UsrSqlEntities();
foreach (string fm in form)
{
if (fm.Contains("PayMonthOne"))
usr.fName = Int32.Parse(form[fm]);
}
db.SaveChanges();
}
I've debugged this in VS2010 and each step passes through with no errors i.e. 'User' exists in my Entity Framework, my 'form' contains a value which passes to 'fName'. However, running SQlProfiler in SSMS 2008 doesn't show any activity (and obviously not record in my database). My entity framework is modeled on this db as, when I do an update to an entity, the changes in the db reflect in the EF.
I don't know why SaveChanges() isn't working. Can somebody help?
Upvotes: 3
Views: 15354
Reputation: 21487
I would recommend the following:
var db=new UsrSqlEntities(); /* Module Level declaration */
[HttpPost]
public ActionResult Create(User usr)
{
db.Users.Add(usr); /* Add usr object to Users DbSet */
db.SaveChanges(); /* Save all changes to the database */
}
This assumes that you are creating a new User, and Users is your DbSet for User objects, and your User object has a property "PayMonthOne" of type int or int?.
Upvotes: 1
Reputation: 836
If you are updating the entity, you will need to connect the usr object to the db context and mark it as modified.
db.Attach(usr);
db.Context.Entry(usr).State = EntityState.Modified;
If it is new you will need to add it via:
db.Add(usr);
Then call your
db.SaveChanges()
Upvotes: 4