Storing binary data with metadata

Using Entity Framework 4.2 Code First we want to store some image data in our database. Images are small and cached on disk whenever we can.

However, quite often we need some metadata stored in the image (for example, the MIME type), but not the actual image data.

public class Item { public int Id { get; set; } //... public Image Image { get; set; } } public class Image { public int Id { get; set; } public String MimeType { get; set; } public byte[] Bytes { get; set; } } // this also loads Bytes: var item = _db.Items.Include("Image").Find(1); var mimeType = item.Image.MimeType; 

In particular, we only want the actual Bytes image in very rare cases, and therefore do not want it to load unless we request it.

What is the best practice for preventing Bytes from loading when you need actual Image objects?

+4
source share
1 answer

My recommendation is that you create a separate object (for example, ImageBytes with identifier and bytes) specifically for the field containing bytes, and make it associated with the Image object (which has Id and MimeType). You can use the "Partition tables" function (in EDMX and in the first code), where you can map multiple objects in one database table. Then you can query for image objects, and EF will select only the columns you need from the database. You can access bytes through the relationships you define between Image and ImageBytes. You can then either download the download, or lazy download, or explicit download to receive images.

If you use data annotations, all you have to do is specify a table for both objects:

 [Table("Image")] public class Image {} [Table("Image")] public class ImageBytes {} 

With smooth API

 modelBuilder.Entity<Image>() .HasRequired(e => e.Bytes) .WithRequiredPrincipal(); modelBuilder.Entity<Image>().ToTable("Image"); modelBuilder.Entity<ImageBytes>().ToTable("Image"); 

NTN Julie

+6
source

Source: https://habr.com/ru/post/1385129/


All Articles