How to store images using Entity Framework Code First CTP 5?

82,736

Solution 1

You can't use SQL FILESTREAM in EF. EF is supposed to work on top of different database servers but filestream feature is specific feature of SQL 2008 and newer. You can try to do it old way - use varbinary(max) in your database table and use byte array in your mapped class.

Edit:

Little clarification - you can use FILESTREAM in the database but EF will not take advantage of streaming. It will load it as standard varbinary(max).

Solution 2

I always create another class like ProductImage with a one-to-one association in order to manage lazy loading and also to normalize the table:

public class ProductImage
{
    public int ProductId { get; private set; }
    public byte[] Image { get; set; }
}

Solution 3

Just declare your property as byte[] as Ladislav mentioned.

public class Product
{
    public int Id { get; private set; }

    public string Name { get; set; }

    public byte[] ProductImage { get; set; }
}

That is pretty much it. If you don't map the property the convention is it maps to a varbinary(max). If you have an image column in the database already just add [Column(TypeName = "image")] on the ProductImage property or if you prefer code mapping add this to your OnModelCreating override in the context class:

modelBuilder.Entity<Product>().Property(p => p.ProductImage).HasColumnType("image");

The problem I have with it is that I have not found a way to make the property lazy as I don't necessarily want to load binary data every time I fetch a product. I not sure I recall correctly but NHibernate can do it out of the box.

Share:
82,736

Related videos on Youtube

Max Schmeling
Author by

Max Schmeling

Node.js and Ruby on Rails web and back-end developer.

Updated on January 06, 2020

Comments

  • Max Schmeling
    Max Schmeling over 4 years

    I'm just trying to figure out if there is a simple way to store and retrieve binary (file) data using EF Code First CTP 5? I would really like it to use the FILESTREAM type, but I'm really just looking for some way to make it work.

  • user3431501
    user3431501 over 10 years
    Yes, NHibernate can do the column-specific lazy-loading out of the box: ayende.com/blog/4377/nhibernate-new-feature-lazy-properties.
  • C.List
    C.List over 8 years
    Wouldn't it be much simpler to create a view that doesn't include the file image column and then create a second entity in EF that points to the view instead of the table - say, e.g. "ProductLite"
  • Greg Gum
    Greg Gum over 8 years
    @C.List I can't believe I have been using EF for years and never thought of doing that. It's a fabulous idea and I just put it to use, getting rid of an unnecessary view that I was using to do the same thing. Let's call it a "virtual entity" :)