【发布时间】:2017-07-11 14:36:28
【问题描述】:
我正在使用 MVC 5 和实体框架 6 我的模型包含一个必需的属性
public class Slider
{
public int id { get; set; }
[NotMapped]
[ValidateFileAttributeForImages(ErrorMessageResourceName = "SliderFileError", ErrorMessageResourceType = typeof(GlobalRes))]
[Display(Name = "SliderFile", ResourceType = typeof(GlobalRes))]
public HttpPostedFileBase File { get; set; }
public string ImagePath { get; set; }
}
我需要删除此必需的数据注释,以便我可以更新或编辑此模型,因为我用户可以在编辑中上传或不上传图像..所以我找到了这篇文章Disable Required validation attribute under certain circumstances
所以我做了一个 ViewModel 包含相同的属性,但没有必需的。
public class SliderEditViewModel
{
public int id { get; set; }
[NotMapped]
[Display(Name = "SliderFile", ResourceType = typeof(GlobalRes))]
public HttpPostedFileBase File { get; set; }
public string ImagePath { get; set; }
}
在我的行动结果中
public ActionResult EditSliderLayer(SliderEditViewModel slider, string Comand, HttpPostedFileBase File)
{
using (DBContext db = new DBContext())
{
if (ModelState.IsValid)
{
if (Comand == GlobalRes.EditBTN)
{
db.Entry(slider).State = EntityState.Modified;
db.SaveChanges(); <!-- here i got error -->
return View();
}
else if (Comand == GlobalRes.DeleteBTN)
{
}
}
List<Slider> SliderName = db.Slider.ToList();
ViewBag.SliderLayerName = new SelectList(SliderName, "id", "Header");
return View(slider);
}
}
我收到错误
实体类型 SliderEditViewModel 不是当前上下文模型的一部分。
ValidateFileAttributeForImages
public class ValidateFileAttributeForImages : RequiredAttribute
{
public override bool IsValid(object obj)
{
var file = obj as HttpPostedFileBase;
if (file == null)
{
return false;
}
if (file.ContentLength > 1 * 1024 * 1024)
{
return false;
}
try
{
if (Path.GetExtension(file.FileName) == ".png" || Path.GetExtension(file.FileName) == ".jpg" ||
Path.GetExtension(file.FileName) == ".jpeg" || Path.GetExtension(file.FileName) == ".bmg ")
{
return true;
}
}
catch
{
}
return false;
}
}
【问题讨论】:
-
您需要将视图模型映射到数据模型的实例。并且视图模型中的
[NotMapped]属性没有任何意义(无论如何,视图模型都与 EF 无关 - What is ViewModel in MVC?)。作为旁注,您的属性不正确,建议您阅读this answer
标签: c# asp.net-mvc asp.net-mvc-5 entity-framework-6