如何使用Entity Framework Code First CTP 5存储图像?
我只是想弄清楚是否有一种简单的方法可以使用 EF Code First CTP 5 存储和检索二进制(文件)数据?我真的很希望它使用 FILESTREAM 类型,但我真的只是在寻找某种方法让它工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我总是创建另一个具有一对一关联的类,例如
ProductImage
,以便管理延迟加载并规范化表: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:正如 Ladislav 所说,只需将您的属性声明为 byte[] 即可。
差不多就是这样了。如果您不映射该属性,则约定将其映射到
varbinary(max)
。如果数据库中已有图像列,只需在 ProductImage 属性上添加
[Column(TypeName = "image")]
,或者如果您更喜欢代码映射,请将其添加到上下文类中的 OnModelCreating 重写中:我遇到的问题是,我还没有找到一种方法来使属性变得惰性,因为我不一定希望每次获取产品时都加载二进制数据。
我不确定我是否记得正确,但 NHibernate 可以开箱即用。
Just declare your property as byte[] as Ladislav mentioned.
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: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.
您不能在 EF 中使用 SQL
FILESTREAM
。 EF 应该在不同的数据库服务器之上工作,但文件流功能是 SQL 2008 及更高版本的特定功能。您可以尝试使用旧方法 - 在数据库表中使用 varbinary(max) 并在映射类中使用字节数组。编辑:
一点澄清 - 您可以在数据库中使用
FILESTREAM
,但 EF 不会利用流式传输。它将作为标准varbinary(max)
加载。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 - usevarbinary(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 standardvarbinary(max)
.