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?
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);
}
}
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 .....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With