在我的方法更新我的记录时出错如下

时间:2015-06-04 14:58:16

标签: asp.net-mvc-4

我在这段代码中做错了什么? (我使用的是MVC4和EF) 举个例子:请清楚这是更新鲜的使用MVC4

EditResponse response = new EditResponse();
try
{
    using (WeMatchContext db = new WeMatchContext())
    {
        B_MEMBER_REGISTER update = new B_MEMBER_REGISTER();
        var output = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
        if(output != null )
        {
        update.FIRST_NAME = model.FIRST_NAME;
        update.LAST_NAME = model.LAST_NAME;
        update.GENDER = model.GENDER;
        update.DOB = model.DOB;

        int resultcount = db.SaveChanges();                    
        if (resultcount > 0)
        {
            response.MEMBER_ID = update.MEMBER_ID;
            response.ResultCode = 0;
            response.Message = "Updated Successfully";

        }                 

1 个答案:

答案 0 :(得分:0)

您必须将更新的数据附加到db实体。请试试这个,

using (WeMatchContext db = new WeMatchContext())
{        
    var update = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
    if(update != null )
    {
        update.FIRST_NAME = model.FIRST_NAME;
        update.LAST_NAME = model.LAST_NAME;
        update.GENDER = model.GENDER;
        update.DOB = model.DOB; 

        //below line of code is very important. 
        db.B_MEMBER_REGISTER.Attach(update);
        db.Entry(update).State = EntityState.Modified;

        int resultcount = db.SaveChanges();                    
        if (resultcount > 0)
        {
             response.MEMBER_ID = update.MEMBER_ID;
             response.ResultCode = 0;
             response.Message = "Updated Successfully";    
        }
   }
}