【发布时间】:2023-04-02 09:01:01
【问题描述】:
我一直在关注 Apress Pro ASP.NET MVC 3 Framework 书中的 SportsStore 示例项目,并尝试将这些概念应用到我的应用程序中。困扰我的一个方面是,在示例中,我可以将图像添加到产品中并将其保存到数据库中,但是如果我编辑任何给定的产品,而不为它上传新图像,图像数据将被清除.我希望能够编辑产品,但如果从 HTTP 帖子返回的图像数据为空,我希望 Entity Framework 保留现有的图像数据(和内容类型)。如果未上传新图像,如何命令 EF 不将该图像字段更新为 null?
[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();
}
}
}
型号
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; }
}
【问题讨论】:
-
为您的
if (image1 != null)语句添加一个else(当图像为空时),并从数据库表中获取图像并为您设置新模型。 -
当我想改变一些东西,例如名字,我上传了一张照片,但它没有改变,它从数据库中删除
标签: c# asp.net asp.net-mvc entity-framework file-upload