Entity Framework Code First Table Splitting

Since Entity Framework does not support lazy scalar properties, only lazy references and collections, in order to avoid automatic loading of columns with large contents – BLOBs or CLOBs – we can use a technique called table splitting. In a nutshell, this means using multiple entities to store the columns of a table, say, one for the core, and another for the heavy columns.

Let’s say we have the following class model:

image

The code might look like this, using mapping attributes:

   1: [Table("Core")]
   2: public class Detail
   3: {
   4:     [Key]
   5:     [ForeignKey("Core")]
   6:     public Int32 CoreId
   7:     {
   8:         get;
   9:         set;
  10:     }
  11:  
  12:     [Required]
  13:     public Core Core
  14:     {
  15:         get;
  16:         set;
  17:     }
  18:  
  19:     public String HeavyProperty
  20:     {
  21:         get;
  22:         set;
  23:     }
  24: }
  25:  
  26: public class Core
  27: {
  28:     public Int32 CoreId
  29:     {
  30:         get;
  31:         set;
  32:     }
  33:  
  34:     public Int32 RegularProperty
  35:     {
  36:         get;
  37:         set;
  38:     }
  39:  
  40:     [Required]
  41:     public virtual Detail Detail
  42:     {
  43:         get;
  44:         set;
  45:     }
  46: }

It can also be configured with fluent mapping:

   1: protected override void OnModelCreating(DbModelBuilder modelBuilder)
   2: {
   3:     modelBuilder.Entity<Core>().HasRequired(p => p.Detail).WithRequiredPrincipal(a => a.Core);
   4:     modelBuilder.Entity<Detail>().HasRequired(p => p.Core).WithRequiredPrincipal(a => a.Detail);
   5:     modelBuilder.Entity<Detail>().ToTable("Core");    
   6:  
   7:     base.OnModelCreating(modelBuilder);
   8: }

You will notice that both properties need to be marked as required, this is a requirement for table splitting in EFCF. The Detail property is naturally lazy loaded and so is the HeavyProperty.

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website