【问题标题】:Value cannot be null. Parameter name: entitySet [duplicate]值不能为空。参数名称:entitySet [重复]
【发布时间】:2017-05-05 10:07:21
【问题描述】:
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; }
  }

}

这是我的数据访问代码:

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

这是我的观点:

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

每次我更新数据库或在浏览器中运行代码时,都会出现以下错误:

“值不能为空。参数名称:entitySet”。

这里是调用栈:

      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)

但是当我注释掉 ExtendedNewsModel 类时,它会更新数据库并在浏览器中运行。

我想知道我做错了什么,或者是否有另一种方法可以使用 HttpPostedFileBase 而无需将其放入类中,以及如何将其呈现到视图中。

【问题讨论】:

  • 发布 full 异常,包括它的调用堆栈和引发它的代码。您只发布了两个数据类,没有任何可以抛出任何东西的方法。您只需调用 Exception.ToString() 即可获得完整的异常
  • 您收到的错误不在您发布的代码中
  • BTW HttpPostedFileBase 与数据库无关。错误消息抱怨entitySet。发布您的数据访问代码

标签: c# asp.net model-view-controller


【解决方案1】:

我认为您不能使用此处编码的 HttpPostedFileBase,此类仅用于操作使用 Form Data 方法接收的文件。

如果您尝试在视图中显示文件,您可以将其转换为 base64 字符串并将其作为属性与视图模型一起发送(我通常不推荐这种方法),或者最佳做法是显示文件(在您的情况下为图片)是通过使用 URL 引用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2014-05-17
    相关资源
    最近更新 更多