SaveChanges()不保存数据 [英] SaveChanges() not saving data

查看:419
本文介绍了SaveChanges()不保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触MVC,所以请耐心等待。这是我正在处理的MVC项目中控制器中的操作代码:

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();
}

我已经在VS2010中对此进行了调试,并且每个步骤都没有错误通过我的实体框架中存在用户,我的表单包含一个传递给 fName的值。但是,在SSMS 2008中运行SQlProfiler不会显示任何活动(并且显然不会记录在我的数据库中)。我的实体框架以此数据库为模型,因为当我对实体进行更新时,数据库中的更改反映在EF中。

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.

我不知道为什么SaveChanges()无法正常工作。有人可以帮忙吗?

I don't know why SaveChanges() isn't working. Can somebody help?

推荐答案

如果要更新实体,则需要将usr对象连接到db上下文并标记它被修改。

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);

然后致电

db.SaveChanges()

这篇关于SaveChanges()不保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆