I have been following the SportsStore example project in Apress Pro ASP.NET MVC 3 Framework book and trying to apply the concepts to my application. One area that is bugging me is that in the sample, I can add an image to a product and it gets saved to the database, but if I edit any given product, without uploading a new image for it, the image data is cleared out. I want to be able to edit a product, but if the image data returned from the HTTP post is null, that I want Entity Framework to keep the exisiting image data (and content type). How can I command EF to not update this image field with null if a new image isn't uploaded?
[HttpPost]
public ActionResult Edit(int id, HttpPostedFileBase image1, FormCollection collection)
{
using (ISession session = Database.OpenSession())
{
try
{
DoctorsModel db = new DoctorsModel();
db.Id_d = id;
db.D_city = collection["D_city"].ToString();
db.D_egn = collection["D_egn"].ToString();
db.D_email = collection["D_email"].ToString();
db.D_family_name = collection["D_family_name"].ToString();
db.D_first_name = collection["D_first_name"].ToString();
db.D_gender = collection["D_gender"].ToString();
db.D_mid_name = collection["D_mid_name"].ToString();
db.D_phone = collection["D_phone"].ToString();
db.D_specialty = collection["D_specialty"].ToString();
db.D_room = collection["D_room"].ToString();
db.D_floor = collection["D_floor"].ToString();
if (image1 != null)
{
db.D_picture = new byte[image1.ContentLength];
image1.InputStream.Read(db.D_picture, 0, image1.ContentLength);
}
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(db);
transaction.Commit();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
Model
public class DoctorsModel
{
public virtual int Id_d { get; set; }
[Display (Name ="Име: ")]
public virtual string D_first_name { get; set; }
[Display(Name = "Презиме: ")]
public virtual string D_mid_name { get; set; }
[Display(Name = "Фамилия: ")]
public virtual string D_family_name { get; set; }
[Display(Name = "Специалност: ")]
public virtual string D_specialty { get; set; }
[Display(Name = "Пол: ")]
public virtual string D_gender { get; set; }
[Display(Name = "Тел.номер: ")]
public virtual string D_phone { get; set; }
[Display(Name = "Email: ")]
public virtual string D_email { get; set; }
[Display(Name = "ЕГН: ")]
public virtual string D_egn { get; set; }
[Display(Name = "Град: ")]
public virtual string D_city { get; set; }
[Display(Name = "Снимка: ")]
public virtual byte[] D_picture { get; set; }
[StringLength(5)]
public virtual string D_rating { get; set; }
public virtual string D_content { get; set; }
[Display(Name = "Стая:" )]
public virtual string D_room { get; set; }
[Display(Name = "Етаж: ")]
public virtual string D_floor { get; set; }
}