I am struggling to implement a simple 'update profile' functionality(learning purposes). I simply want to be able not to update the profile image everytime I update a give profile. When the picture is there and some other part of the profile is update I want the picture to stay the same.
I came up with the following code for this :
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "UserDetailsId,ImageData,FirstName,LastName,UserAddress,UserCountry,UserPostalCode,UserPhoneNumber,CompanyId,identtyUserId")] UserDetails userDetails, HttpPostedFileBase UploadImage)
{
if (ModelState.IsValid)
{
if (UploadImage!=null) {
byte[] buf = new byte[UploadImage.ContentLength];
UploadImage.InputStream.Read(buf, 0, buf.Length);
userDetails.ImageData = buf;
}
else {
var userFromDb = db.UsersDetails.Where(u => u.identtyUserId == userDetails.identtyUserId).First();//i am getting the old user data
userDetails.ImageData = userFromDb.ImageData; //saving the image to the modified state
}
db.Entry(userDetails).State = EntityState.Modified;//error here
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName", userDetails.CompanyId);
return View(userDetails);
The error I am getting on this row db.Entry(userDetails).State = EntityState.Modified;
is the following :
Attaching an entity of type 'eksp.Models.UserDetails' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
The model :
public class UserDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserDetailsId { get; set; }
public byte[] ImageData { get; set; }
[NotMapped]
public HttpPostedFileBase UploadImage { get; set; }
[NotMapped]
public string ImageBase64 => System.Convert.ToBase64String(ImageData);
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserPhoneNumber { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
public string identtyUserId { get; set; }
public virtual ICollection<WorkRolesUsersDetails> WorkRolesUsersDetails { get; set; }
Although it may looke pretty self explenatory for me it is not clear this is happening?
Can somebody guide me how to achieve what I want to achieve?
Thanks!