EntityType'HttpPostedFile'没有定义键

时间:2013-10-24 10:44:56

标签: c# asp.net-mvc entity-framework

当我启动我的MVC应用程序时,这个错误来自upp “EntityType'HttpPostedFile'没有定义键”

有人可以告诉我这里有什么不对吗?

型号:

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

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:0)

您的ORM(此处为probaly EF)认为HttpPostedFile是您数据库中的实体,而ImageData是导航属性。

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

相关问题