make byte[] property load lazy

2019-02-18 12:52发布

问题:

I'm using EF4 Code First and I have a property:

public byte[] Bytes {get;set;}

can I make this property load lazily ( only when it's needed) ?

回答1:

Table spliting works in EF 4.1 RC:

public class Item
{
    public int Id { get; set; }
    ...
    public virtual ItemDetail ItemDetail { get; set; }
}

public class ItemDetail
{
    public int Id { get; set; }
    public byte[] Bytes { get; set; }
}

public class Context : DbContext
{
    public DbSet<Item> Items { get; set; }
    public DbSet<ItemDetail> ItemDetails { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Item>().ToTable("Items");
        modelBuilder.Entity<ItemDetail>().ToTable("Items");
        modelBuilder.Entity<Item>()
            .HasRequired(i => i.ItemDetail)
            .WithRequiredPrincipal();
    }
}


回答2:

That's indeed an old common request since EF 1, EF 4 and still in EF 4.1.

The link is related to CTP5 and the only possible solution is Table Splitting. You basically need to define two entity classes but map them to one single table in the database. The task to load the byte[] is then reduced to loading a normal navigation property.

The answer in the post talks about a bug in CTP5 which made Table splitting not working correctly but which is hopefully fixed now in EF 4.1 RC (but I don't know if it's really fixed).