0

当我启动我的 MVC 应用程序时,出现此错误“EntityType 'HttpPostedFile' has no key defined”

有人可以告诉我这里有什么问题吗?

模型:

public partial class Advert
{
    [Key]
    public int ID { get; set; }

    [Required]
    public HttpPostedFile ImageData { get; set; }

    [Required]
    public string UrlToUse { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public int SchemaType { get; set; }

    public string Title { get; set; }
}

当控制器被击中时,我运行它

    public ActionResult DisplayAdvert()
    {
        db.Database.CreateIfNotExists();

        return PartialView("_Advert");
    }

并且繁荣,在行 db.Database.CreateIfNotExists(); 它失败:

Boat_Club.Models.HttpPostedFile: : EntityType 'HttpPostedFile' 没有定义键。定义此 EntityType 的键。HttpPostedFiles:EntityType:EntitySet 'HttpPostedFiles' 基于没有定义键的类型'HttpPostedFile'。

我已经搜索了一些答案,并且都说我必须将 [Key] 添加到模型中,而且我有,那么这里发生了什么?

我正在使用 Visual Studio Express 2013 for Web,以及所有最新版本的 MVC 和 EF。

/谢谢

这虽然有效!

public partial class Advert
{
    [Key]
    public int ID { get; set; }

    [Required]
    public byte[] ImageData { get; set; }

    [Required]
    public string UrlToUse { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public int SchemaType { get; set; }

    public string Title { get; set; }
}
4

2 回答 2

0

首先不要HttpPostedFile在你的模型中使用,它不应该在任何地方被序列化。

而是将您的图像数据声明为byte[],或者如果您需要更多详细信息并创建另一种类型来保存这些数据,然后从发布的文件实例传输所需的详细信息。

例如:

public partial class Advert
{
    [Key]
    public int ID { get; set; }

    [Required]
    public byte[] ImageData { get; set; }

    [Required]
    public string UrlToUse { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public int SchemaType { get; set; }

    public string Title { get; set; }
}
于 2013-10-24T10:46:11.423 回答
0

您的 ORM(此处可能是 EF)认为这HttpPostedFile是您数据库中的一个实体,并且ImageData是一个导航属性。

当您在控制器中获取HttpPostedFileorHttpPostedFileBase时,您应该将其内容作为 a 获取byte[],然后将其传递给您的Advert实体。这是一个例子:http: //msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream (v=vs.110).aspx

于 2013-10-24T10:54:49.910 回答