0
votes

When I start my MVC App, this error comes upp "EntityType 'HttpPostedFile' has no key defined"

Can someone please tell me whats wrong here?

Model:

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

When the controller get hit, I run this

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

        return PartialView("_Advert");
    }

And boom, at the line db.Database.CreateIfNotExists(); it fails:

Boat_Club.Models.HttpPostedFile: : EntityType 'HttpPostedFile' has no key defined. Define the key for this EntityType. HttpPostedFiles: EntityType: EntitySet 'HttpPostedFiles' is based on type 'HttpPostedFile' that has no keys defined.

I've searched for some answers, and all says that I have to add [Key] to the Model, and I have, so what is going on here??

I'm using Visual Studio Express 2013 for Web, with all the latets versions of MVC and EF.

/Thanks

This works though!!

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

2 Answers

0
votes

Firstly do not use HttpPostedFile in your model, it's not supposed to be serialized anywhere.

Instead declare your image data as byte[], or if you need more details as well create another type to hold those, then transfer the required details across from the posted file instance.

For example:

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

Your ORM (probaly EF here) believes that HttpPostedFile is an entity from your database, and that ImageData is a navigation property.

When you get an HttpPostedFile or HttpPostedFileBase in your controller, you should get its content as a byte[], then pass it to your Advert entity. Here's an exemple : http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream(v=vs.110).aspx