Musarrat Saeed
Musarrat Saeed

Reputation: 83

ModelValidationException - MVC Codefirst

I created controller using entity framework it gave error I commented the HttpPostedFileBase attribute from the class below and tried again, it worked and all the CRUD views were generated. Now when I'm trying to add a new station using following code:

    [HttpPost]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public ActionResult Create(Station station)
    {
        station.FileName = station.File.FileName;
        station.ImageSize = station.File.ContentLength;
        byte[] data = new byte[station.File.ContentLength];
        station.File.InputStream.Read(data, 0, station.File.ContentLength);
        station.ImageData = data;

            db.Stations.Add(station);
            db.SaveChanges();

        return RedirectToAction("Index");
    }

it gives exception (shown below):

System.Data.Entity.ModelConfiguration.ModelValidationException was unhandled by user code HResult=-2146233088 Message=One or more validation errors were detected during model generation:

MetroTrain.Models.HttpPostedFileBase: : EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType. HttpPostedFileBases: EntityType: EntitySet 'HttpPostedFileBases' is based on type 'HttpPostedFileBase' that has no keys defined.

Source=EntityFramework StackTrace: at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate() at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() at System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity) at System.Data.Entity.DbSet1.Add(TEntity entity) at MetroTrain.Controllers.StationsController.Create(Station station) in c:\Users\ghousia pc\Desktop\MetroTrain\MetroTrain\Controllers\StationsController.cs:line 58 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End() at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3c() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.b__3e() InnerException:

The class used (for scaffolding):

 public class Station
    {
        [Key]
        public int Id { get; set; }
        [Display(Name="Station Name")]
        public string StationName { get; set; }
        public double Distance { get; set; }
        [DataType(DataType.PhoneNumber)]
        public string Mobile { get; set; }
        [DataType(DataType.Date)]
        public DateTime Opening { get; set; }
        public string Connections { get; set; }
        public string Layout { get; set; }
        [Display(Name="Tourists Place")]
        public string TouristsPlace { get; set; }
        [Display(Name = "Tourists Place Image")]
        /////////
        public int ImageId { get; set; }
        public Nullable<int> ImageSize { get; set; }
        public string FileName { get; set; }
        public byte[] ImageData { get; set; }

        [Required(ErrorMessage = "Please select file")]
        public HttpPostedFileBase File { get; set; }
        /// <summary>
        /// ////
        /// </summary>
        [Display(Name="Line Color")]
        public string LineColor { get; set; }
    }

Upvotes: 0

Views: 449

Answers (1)

Ax El Paluku
Ax El Paluku

Reputation: 26

MAke sure you add an attribute [NotMapped] like this.

[NotMapped]
public HttpPostedFileBase File { get; set; }

Upvotes: 1

Related Questions