Map Image type property using Entity Framework Core

727 Views Asked by At

I have a class with a property of type System.Drawing.Image because I want to store images in it. When trying to scaffold a Web API controller with Entity Framework Core I get the error message:

Image of the error

I think the problem is that the System.Drawing.Image class has a "Tag" property of type object. Now, the question is how do I fix this mapping?

1

There are 1 best solutions below

0
Martin Staufcik On BEST ANSWER

Option 1:

Instead of using System.Drawing.Image directly in EF mapping, you could map the data to another property of type byte[]

[NotMapped]
public System.Drawing.Image Image { get; set; }

public byte[] ImageData 
{
    get 
    {
        using (var ms = new MemoryStream())
        {
            Image.Save(ms, Image.RawFormat);
            return ms.ToArray();
        }
    }
    set  
    {
        if (value == null)
        {
            Image = null;
        }
        else
        {
            using (var ms = new MemoryStream(value))
            {
                Image = Image.FromStream(ms);
            }
        }
    }
}

Option 2:

You could also leave only the ImageData property in the model and handle loading and saving the image outside the model.

public byte[] ImageData { get; set; }