2
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

  namespace Church_On_The_Rock.Models
{
   public class News
 {
    public int NewsId { get; set; }
    public string Title { get; set; }
    public string Writer { get; set; }
    [DisplayFormat(DataFormatString = "{0:MMMM dd, yyyy}", 
     ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }
    public byte[] Picture { get; set; }

    public string Blog { get; set; }

  }
     //I know the problem is here but don't know what to do 
    public class ExtendedNewsModel: News
  {
    public HttpPostedFileBase postedPicture { get; set; }
  }

}

Here is my Data access code:

public ActionResult Create(ExtendedNewsModel news)
    {
        if (ModelState.IsValid)
        {
            if (news.postedPicture != null)
            {

                if (news.postedPicture.ContentLength > (8 * 1024 * 1024))
                {
                    ModelState.AddModelError("CustomError", "Image can not be larger than 8MB.");
                    return View();
                }
                if (!(news.postedPicture.ContentType == "image/jpeg" || news.postedPicture.ContentType == "image/png" || news.postedPicture.ContentType == "image/gif"))
                {
                    ModelState.AddModelError("CustomError", "Image must be in jpeg,png or gif format");
                }

            }
            byte[] data = new byte[news.postedPicture.ContentLength];
            news.postedPicture.InputStream.Read(data, 0, news.postedPicture.ContentLength);
            news.Picture = data;
            db.New.Add(news);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(news);
    }

Here is my View:

 @model Church_On_The_Rock.Models.ExtendedNewsModel

  @{
    ViewBag.Title = "Create";
  }
   @using (Html.BeginForm("Create","Home", FormMethod.Post, new {role = "form", enctype = "multipart/form-data"}))
  {

    @Html.AntiForgeryToken()
     <div class="form-group createforms">
       <span>@Html.LabelFor(model => model.Picture, htmlAttributes: new { 
       @class = "Control-label col-md-2" })</span>
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.postedPicture,  new {type 
         ="file" })
            @Html.ValidationMessage("customMessage") 
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10 createbutton">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
    }

Every time I update the database or run the code in a browser, it gives me this error:

"Value cannot be null. Parameter name: entitySet".

Here is the call stack:

      System.ArgumentNullException: Value cannot be null.
Parameter name: entitySet
   at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName)
   at System.Data.Entity.Core.Mapping.EntitySetMapping..ctor(EntitySet entitySet, EntityContainerMapping containerMapping)
   at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.AddEntitySetMapping(DbDatabaseMapping databaseMapping, EntitySet entitySet)
   at System.Data.Entity.ModelConfiguration.Edm.Services.TableMappingGenerator.Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
   at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateEntityTypes(DbDatabaseMapping databaseMapping)
   at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel)
   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.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
   at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
   at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
   at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
   at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)

But when I comment out The class ExtendedNewsModel, it updates the database and runs in a browser.

I want to know what I am doing wrong or if there is another way to just use HttpPostedFileBase without putting it in a class and also how to render it to a View.

umeh oscar
  • 139
  • 9
  • Post the *full* exception, including its call stack, and the code that throws it. You only posted two data classes without any methods that could throw anything. You can get the full exception simply by calling `Exception.ToString()` – Panagiotis Kanavos May 05 '17 at 10:17
  • The error you're getting is not in the code you've posted – Jamiec May 05 '17 at 10:18
  • BTW `HttpPostedFileBase` has nothing to do with the database. The error message complains about `entitySet`. Post your data access code – Panagiotis Kanavos May 05 '17 at 10:18

1 Answers1

-1

I don't think you can use HttpPostedFileBase as coded here, this class is used only to manipulate a file received using Form Data method.

If you are trying to show a file in a view, you either convert into a base64 string and send it as property with the View Model (I don't recommend this method usually), or the best practice is to show the file (a picture in your case) is by referencing it using a URL.