entity-frameworkado.netmappingentity-framework-4.1system.drawing.imaging

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?


Solution

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