实体框架不保存到数据库

时间:2016-11-30 20:29:53

标签: entity-framework

我有一个挑战,我正在尝试从数据库更新记录但它没有保存到数据库,并且没有显示任何错误,它给出一条消息,它已更新记录,但没有更改数据库。我的代码如下。任何建议

dbEntities context = new dbEntities();

var query = context.ConsultantsProfiles.SingleOrDefault(c => c.Username == username);

        if (query != null)
        { 

          query.Summary = txtSummary.Text;
          query.CareerTitle = txtTitle.Text;
          query.ConsultantType = cbType.Text;
          query.Username = username;
          query.FirstName = txtFirstname.Text;
          query.LastName = txtLastName.Text;
          query.Email = txtEmail.Text;
          query.DateofBirth = Convert.ToDateTime(dptDateofBirth.Value);
          query.PhoneNumber = txtPhoneNumber.Text;
          query.Website = txtWebsite.Text;
          query.Town = txtTown.Text;
          query.Country = txtCountry.Text;

          if (FileUpload1.HasFile)
          {
            //image upload
            HttpPostedFile postedFile = FileUpload1.PostedFile;
            // HttpPostedFile postedFile = uploadControl.UploadedFiles[i];
            Stream stream = postedFile.InputStream;
            BinaryReader reader = new BinaryReader(stream);
            byte[] imgByte = reader.ReadBytes((int)stream.Length);
            int imglength = FileUpload1.PostedFile.ContentLength;

            query.ProfilePhoto = imgByte;

          }



          context.ConsultantsProfiles.Attach(query);
          context.Entry(query).State = EntityState.Modified;
          context.SaveChanges();
        }
        Response.Write("<script language=javascript>alert('Notification: The Profile Has been Updated');</script>");
        }

1 个答案:

答案 0 :(得分:0)

dbEntities context = new dbEntities();
var consultantProfile = new ConsultantProfile
{
    Summary = txtSummary.Text;
    CareerTitle = txtTitle.Text;
    ConsultantType = cbType.Text;
    Username = username;
    FirstName = txtFirstname.Text;
    LastName = txtLastName.Text;
    Email = txtEmail.Text;
    DateofBirth = Convert.ToDateTime(dptDateofBirth.Value);
    PhoneNumber = txtPhoneNumber.Text;
    Website = txtWebsite.Text;
    Town = txtTown.Text;
    Country = txtCountry.Text;
}
if (FileUpload1.HasFile)
{
    //image upload
    HttpPostedFile postedFile = FileUpload1.PostedFile;
    // HttpPostedFile postedFile = uploadControl.UploadedFiles[i];
    Stream stream = postedFile.InputStream;
    BinaryReader reader = new BinaryReader(stream);
    byte[] imgByte = reader.ReadBytes((int)stream.Length);
    int imglength = FileUpload1.PostedFile.ContentLength;

    consultantProfile.ProfilePhoto = imgByte;
}
context.Entry(ConsultantsProfiles).State = EntityState.Modified;
context.SaveChanges();