如何存储图像使用实体框架代码第一 CTP 5?

我只是想知道是否有一个简单的方法来存储和检索二进制(文件)数据使用 EF 代码第一 CTP 5?我真的很希望它使用 FILESTREAM 类型,但我真的只是在寻找一些方法来使它工作。

85531 次浏览

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).

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.

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; }
}