-1

I am using MVC 5 with entity framework 6 I have model contain a Required property

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; }
}

I need to remove this required Data Annotations so I can update or edit this model as I the user can upload an image or not in the edit .. so I found this post Disable Required validation attribute under certain circumstances

so I did a ViewModel contain same properties but without the required.

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; }
}

in my action result

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);
        }

    }

I get error

The entity type SliderEditViewModel is not part of the model for the current context.

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;
    }
}
Community
  • 1
  • 1
kareem khalil
  • 29
  • 2
  • 8
  • You need to map your view model to an instance of the data model. And a `[NotMapped]` attribute in a view model makes no sense (view models are no associated with EF in anyway - [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc)). And as a side note, you attribute is not correct and suggest you read [this answer](http://stackoverflow.com/questions/40199870/how-to-validate-file-type-of-httppostedfilebase-attribute-in-asp-net-mvc-4/40200034#40200034) –  Feb 21 '17 at 21:05

1 Answers1

0

What you need to do is to attach model to DbContext:

db.Sliders.Attach(slider);
db.Entry(slider).State = EntityState.Modified;
db.SaveChanges();

Assuming that your DbSet for Slider object is Sliders.

Based on comments, of this answer, here additional info as there are data model and domain model.

you have Slider model that represents rows in table in database and SliderEditViewModel that you use for form on your View. Now, when user submits data, you get SliderEditViewModel instance (variable slider) but your DbContext needs instance of Slider. So, do following:

Slider dbSlider = new Slider();
dbSlider.Name = slider.Name;
dbSlider.Whatever = slider.Whatever;
....  
db.Sliders.Attach(dbSlider);
db.Entry(dbSlider).State = EntityState.Modified;
db.SaveChanges();
Shadowed
  • 956
  • 7
  • 19
  • i tried this one but gives me error cannot convert from 'M.ViewModel.SliderEditViewModel' to 'M.Models.Slider' – kareem khalil Feb 21 '17 at 19:54
  • That means that you are using different database model and MVC model so you will have to convert from one to another. Make new instance of Slider and copy properties from instance of SliderEditViewModel into it. Then do attach, set state to modified and save changes. – Shadowed Feb 21 '17 at 20:08
  • i am sorry i am confused can you help me with an example . – kareem khalil Feb 21 '17 at 21:27
  • Sure. OK, you have `Slider` model that represents rows in table in database and `SliderEditViewModel` that you use for form on your View. Now, when user submits data, you get `SliderEditViewModel` instance (variable `slider`) but your DbContext needs instance of Slider. So, do following: Slider dbSlider = new Slider(); dbSlider.Name = slider.Name; dbSlider.Whatever = slider.Whatever; .... db.Sliders.Attach(dbSlider); db.Entry(dbSlider).State = EntityState.Modified; db.SaveChanges(); – Shadowed Feb 21 '17 at 22:01
  • Check answer again. I added more info as it is not nicely formatted in comment. – Shadowed Feb 21 '17 at 22:05
  • ok .. now i did every thing lik you said but still getting error " Validation failed for one or more entities. See 'EntityValidationErrors' property for more details" when i checked EntityValidationErrors i found file property – kareem khalil Feb 22 '17 at 15:06