Skip to main content
.NET 6.0+

BLOB Image Properties in EF Core

  • 2 minutes to read

You can declare image properties as a byte array property, or as a reference properties of the MediaDataObject type (available in the Business Class Library).

Image as a Byte Array

The example below illustrates how to implement image properties in an Entity Framework Core Code-First class. Declare a byte array property and apply the ImageEditorAttribute to it. Optionally, you can customize the behavior of the image editor using the attribute’s parameters.

using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
// ...
[DefaultClassOptions]
public class Employee : BaseObject {
    [ImageEditor(ListViewImageEditorMode = ImageEditorMode.PopupPictureEdit,
        DetailViewImageEditorMode = ImageEditorMode.DropDownPictureEdit)]
    public virtual byte[] Photo { get; set; }
}

// Make sure that you use options.UseChangeTrackingProxies() in your DbContext settings.

Refer to the ImageEditorAttribute topic for details on parameters passed to the ImageEditor attribute in the code above. You can also specify image options using the following properties in the Model Editor:

Tip

When an application displays a lot of large images in a List View, it may consume a lot of memory. It is mostly true for ASP.NET Web Forms applications with many simultaneously connected clients. To improve the performance, you can use lazy loading.

Image as a MediaDataObject

The example below illustrates how to implement image properties of the MediaDataObject type (available in the Business Class Library) in an Entity Framework Core class. Image Property Editors are used automatically for properties of the MediaDataObject type, no attributes are required (however, you still can apply the ImageEditorAttribute to customize the editor’s options, as it is demonstated above for byte arrays). The use of this type reduces traffic because images are cached in the browser cache (compared to images of the byte[] type). The delayed loading is always used for MediaDataObject properties.

using DevExpress.ExpressApp;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl.EF;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// ...
[DefaultClassOptions]
public class Contact : BaseObject {
    // ...
    public virtual string Name { get; set; }
    public virtual MediaDataObject Photo { get; set; }
}

// Make sure that you use options.UseChangeTrackingProxies() in your DbContext settings.
See Also