System.Drawing.Image EntityType 'Image' object does not have a key. Define a key for this EntityType

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

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

When initializing a database context for creating a database, the following errors occur:

System.Data.Edm.EdmEntityType :: EntityType 'Image' does not have a key. Define a key for this EntityType.

System.Data.Edm.EdmEntitySet: EntityType: EntitySet images are based on the type of Image that has no keys defined.

Any ideas on how to do this?

+4
source share
2 answers

After @Gats answer - you cannot map all classes to EF. EF understands only base types, and each class mapped must either be recognized as an entity or a complex type. Thus, your Impage should be defined as:

 public byte[] Image { get; set; } 

Marking it as byte[] , EF will understand that it should be stored as varbinary on the SQL server. EF does not support custom types or custom initializers, so you cannot tell EF that your Image must be something else.

If you want to open Image as System.Drawing.Image, you can also do something like:

 public System.Drawing.Image GetBitmap() { using (var stream = new MemoryStream(Image)) { return System.Drawing.Image.FromStream(stream); } } 
+9
source

This is due to the fact that EF cannot track a class that is not available to it (for example, System.Drawing.Image), and it sees your image property as its own entity and expects information to be displayed for it (including the primary key).

If you save the image in your database, you would be better off using the binary property, and then add the actual Image property as a read-only property that converts the binary to an image file. System.Drawing.Image is not a data type that can simply be mapped to SQL.

When you have done this and want the property not to display, use the following data annotation:

 [NotMapped] public ..... 
+5
source

All Articles