Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an IFormFile into a View Model in MVC6

I'm trying to create a form with an image upload field and name field, validated with a view model (see below). Problem is when I migrate my database to account for this class or hit play in Visual Studio (starting the site), I get the following error:

InvalidOperationException: The property 'ImageUpload' on entity type 'BallWallWebApp.ViewModels.Slides.CreateSlideViewModel' has not been added to the model or ignored.
Microsoft.Data.Entity.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder)

Code:

using Microsoft.AspNet.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace BallWallWebApp.ViewModels.Slides
{
    public class CreateSlideViewModel
    {
        [Required]
        public int WallId { get; set; }

        [Required]
        [Display(Name = "Slide Name")]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Slide image file")]
        [DataType(DataType.Upload)]
        public IFormFile ImageUpload { get; set; }
    }
}

What am I missing?

like image 934
James Avatar asked Oct 30 '22 05:10

James


1 Answers

Turns out there was nothing wrong with the code, I simply accidentally selected a Data Context Class when creating the view meaning EF started caring about the View Model which it absolutely shouldn't (View Models shouldn't go near a database).

like image 66
James Avatar answered Nov 15 '22 06:11

James