使用HttpPostedFileBase的强类型模型无法生成视图。

3

我希望有人能帮助我。

我使用的是VS 2012和MVC4。

我正在测试一个使用强类型模型的项目,使用了HttpPostedFileBase。当我尝试生成视图时,它会失败并显示以下错误:

---------------------------
Microsoft Visual Studio
---------------------------
Unable to retrieve metadata for 'ImageTest.Models.ImageHandler'. Value cannot be null.

Parameter name: key
---------------------------
OK   
---------------------------

我尝试了一些网络上的建议,尝试卸载并重新安装MVC,但这并没有帮助。这是我的模型:(是的,我已经尝试过在Id上使用[Key],但没有任何区别)

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

namespace ImageTest.Models
{
public class ImageHandler
{
public int Id { get; set; }
public string ImageName { get; set; }
public HttpPostedFileBase File { get; set; }
}
}

我认为这可能是一个上下文问题,但无论我创建自定义上下文还是使用预定义的上下文,我都会得到相同的错误。这是预定义的上下文:

using ImageTest.Models;
using System.Data.Entity;

public class ImageHandlerContext : DbContext
{
public ImageHandlerContext() : base("DefaultConnection")
{
}

public DbSet<ImageHandler> ImageHandler { get; set; }
}

作为一项测试,如果我注释掉以下内容:
// public HttpPostedFileBase File { get; set; }

我可以轻松地搭建视图。这是一个bug吗?我在文档中没有看到任何关于不支持搭建HttpPostedFileBase的信息。请参见:HttpPostedFileBase
提前感谢。
2个回答

2

Stan 步入了正确的轨道。

模型-视图-控制器(MVC)使用实体框架来生成视图。

实体数据模型:原始数据类型

原始数据类型目前在 .NET 4.5 中得到支持,除非定义了复杂数据类型。以下是支持的原始数据类型:

Binary
Boolean
Byte
DateTime
DateTimeOffset
Decimal
Double
Float
Guid
Int16
Int32
Int64
SByte
String
Time

请参阅:复杂类型 以获取有关扩展此功能的更多信息。
谢谢Stan,我点赞。 编辑: 首先需要使用原始数据类型对视图进行脚手架,并稍后向模型添加HttpPostedFileBase以使用文件上传功能。例如,请参见:在MVC 4中上传图像并在表单中显示 此外,您需要在模型中使用(NotMapped):
[NotMapped]
public HttpPostedFileBase File { get; set; }

现在在脚手架创建的Create ActionResult方法中,您的视图表单返回值包含一个可以使用的System.Web.HttpPostedFileWrapper。

简短回答:

1: Create your Code First Model with Primitive Data Types only! Unless you use the [NotMapped] Attribute.
2: Scaffold your View's.
3: If not done so in step 1, Add to your Model the Methods needed.  E.G: public HttpPostedFileBase File { get; set; } using the [NotMapped] Attribute
4: Add to your Database the necessary Table either manually or from the Console.
5: Add the necessary code to your View's and Controller.

这应该足以让您开始工作了...


1
我认为您无法将HttpPostedFileBase作为模型的属性,至少不能通过EntityFramework进行映射和自动脚手架。如果您思考一下,您认为这种属性类型将映射到哪些数据库字段呢?
如果您想实际在数据库中存储二进制数据,请使用以下内容。
public byte[] File { get; set; }

作为您的财产。

谢谢Stan,我认为你的想法是正确的。请参见:链接 MVC模型-视图-控制器必须在模型中具有HttpPostedFileBase才能用于文件上传,但实体框架似乎无法识别其在我所处的上下文中的使用。看来我需要在视图的脚手架之后单独添加它并进行连接。 - Rusty Nail
是的 - 通常你会发现在你的MVC项目中的模型和你的Entity Framework模型中的实体模型有不同的要求,因此必须是不同的对象。 - StanK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接