简体   繁体   English

Map 使用 Entity Framework Core 的图像类型属性

[英]Map Image type property using Entity Framework Core

I have a class with a property of type System.Drawing.Image because I want to store images in it.我有一个 class 类型为System.Drawing.Image的属性,因为我想在其中存储图像。 When trying to scaffold a Web API controller with Entity Framework Core I get the error message:尝试使用 Entity Framework Core 搭建 Web API controller 时,我收到错误消息:

Image of the error错误图片

I think the problem is that the System.Drawing.Image class has a "Tag" property of type object .我认为问题在于System.Drawing.Image class 具有object类型的“标签”属性。 Now, the question is how do I fix this mapping?现在,问题是如何修复这个映射?

Option 1 :选项 1

Instead of using System.Drawing.Image directly in EF mapping, you could map the data to another property of type byte[]而不是直接在 EF 映射中使用System.Drawing.Image ,您可以将数据 map 到另一个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 :选项 2

You could also leave only the ImageData property in the model and handle loading and saving the image outside the model.您也可以只在 model 中保留ImageData属性,并在 model 之外处理加载和保存图像。

public byte[] ImageData { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM