Thursday, April 14, 2011

How to load varbinary(max) fields only when necessary with ADO.NET Entity Framework?

I have a varbinary(max) field in one of my tables but I don't need it every time and I'm looking for a way to fetch it from the database only when necessary. I'm using ADO.NET Entity Framework. How to do that?

From stackoverflow
  • One way would be to project your result set into an anonymous type when you don't need the blob:

    from entity in context.Entities
    select new 
    {
        Field1 = entity.Field1,
        Field2 = entity.Field2
    }
    

    In this example, only Field1 and Field2 will be loaded.

    This method has the disadvantage that you cannot update the returned instance and do context.SaveChanges. Though I would argue that saving an instance without full knowledge of the instance is borderline unsafe. This method is good when you want a long list of return the instances, but will be querying for a single instance, varbinary field and all, before you actually update.

    Emil : Thank you for your assistance. I was looking for something similar to lazy loading of the varbinary field :) but it seems that this isn't possible.
  • The solution was to create a separate table with the varbinary field and make 1-to-1 relationship between the tables

0 comments:

Post a Comment