我的Asp.Net Mvc项目中有以下模型。创建新对象时,还会创建一个包含"选项"one_answers"Foto"的新列表,以便您可以简单地将新的"选项"与"图片"添加到对象中。
public class VehicleModels
{
[Key]
public virtual int Id { get; set; }
public virtual string Naam { get; set; }
public virtual string Merk { get; set; }
public virtual string Brandstof { get; set; }
public virtual string Kleur { get; set; }
public virtual string TypeVanMerk { get; set; }
public virtual string TypeVanTransmissie { get; set; }
public virtual int Kilometerstand { get; set; }
public virtual int Bouwjaar { get; set; }
public virtual int AantalDeuren { get; set; }
public List<Optie> Options { get; set; }
public List<Foto> Fotos { get; set; }
public VehicleModels()
{
Options = new List<Optie>();
Fotos = new List<Foto>();
}
}
我的控制器中有此编辑
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id, HttpPostedFileBase upload)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var VehicleToUpdate = db.VehicleModels.Find(id);
if (TryUpdateModel(VehicleToUpdate))
{
try
{
if (upload != null && upload.ContentLength > 0)
{
if (VehicleToUpdate.Fotos.Any(f => f.VehicleModelsID == VehicleToUpdate.Id))
{
db.Fotos.Remove(VehicleToUpdate.Fotos.First(f => f.VehicleModelsID == VehicleToUpdate.Id));
}
var picture = new Foto
{
FotoNaam = System.IO.Path.GetFileName(upload.FileName),
ContentType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
picture.Content = reader.ReadBytes(upload.ContentLength);
}
VehicleToUpdate.Fotos.Add(picture);
}
db.Entry(VehicleToUpdate).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
return View(VehicleToUpdate);
}
我的问题:
在调试过程中,我发现Edit方法中的这行代码(var VehicleToUpdate = db.VehicleModels.Find(id);
)创建了模型的一个新对象,并似乎将属性绑定到该新对象。但是因为它通过了构造函数,所以这两个列表都被清除了。
当我试图更改对象的图片时,问题就显现出来了,因为列表是空的,它不会删除任何图像,也不会添加新图像,相反,它只是再次添加旧图像,给我留下2倍相同的图像。
我应该在其他地方实例化我的列表吗?如果是的话,合适的地方在哪里?
附带说明:我遵循本教程将图像添加到我的项目中。
var VehicleToUpdate = db.VehicleModels.Find(id);
不应清除这两个列表。它们应该适当地填充。
如果它们没有被填充,并且是空的,那么请检查您的数据库。要么数据不存在。如果数据存在,则外键约束将被破坏。检查并更正。更正数据库后,请更新项目中实体框架的edmx文件中的模型。之后,实体框架应该适当地填充数据,并且图像将更新,而不是添加副本。