Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Drawing.Image EntityType 'Image' has no key defined. Define the key for this EntityType

I'm using EF Code First and Data Scaffolding and have an entity that contains a property of type

public System.Drawing.Image Image { get; set; }

When initialsing the DB context to create the DB i get the following errors:

System.Data.Edm.EdmEntityType: : EntityType 'Image' has no key defined. Define the key for this EntityType.

System.Data.Edm.EdmEntitySet: EntityType: EntitySet Images is based on type Image that has no keys defined.

Any ideas on how to get arround this?

like image 505
Hugo Avatar asked Dec 07 '22 21:12

Hugo


2 Answers

Following @Gats answer - you cannot map all classes to EF. EF understands only basic types and each mapped class must be either recognized as entity or complex type. So your Impage must be defined as:

public byte[] Image { get; set; }

By marking it as byte[] EF will understand that it must be stored as varbinary in SQL server. EF doesn't support custom types or custom initializers so you cannot say EF that your Image should be anything else.

If you want to expose Image as System.Drawing.Image as well you can do something like:

public System.Drawing.Image GetBitmap()
{
    using (var stream = new MemoryStream(Image))
    {
        return System.Drawing.Image.FromStream(stream);
    }
}
like image 103
Ladislav Mrnka Avatar answered Mar 16 '23 00:03

Ladislav Mrnka


This is because EF cannot track a class that's not available to it (like System.Drawing.Image) and it sees your "image" property as being it's own entity and expects mapping information for it (including a primary key).

If you are storing an image in your database, you will be better off using a binary property and then adding the actual Image property as a read only non-mapped property that converts the binary to an image file. System.Drawing.Image is NOT a datatype that can just map to SQL.

When you have done that and you want to prevent a property from being mapped use the following data annotation:

[NotMapped]
public .....
like image 27
Gats Avatar answered Mar 16 '23 00:03

Gats