[英]What is the best way to store byte array in SQL database using NHibernate?
I have an array of bytes in my C# class, and need to persist it into a SQL Server 2005 database using NHibernate. 我的C#类中有一个字节数组,需要使用NHibernate将其持久化到SQL Server 2005数据库中。 What SQL data type should I use for the column, and how do I got about using NHiberante to do the persistance for me?
我应该为该列使用哪种SQL数据类型,以及如何使用NHiberante为我执行持久性? If the answer is a custom NHibernate type, is there any sample code knicking around to do this?
如果答案是自定义NHibernate类型,是否有示例代码在附近这样做?
Would it just be easier to convert the byte array to a string and persist it in a varcahr column? 将字节数组转换为字符串并将其保存在varcahr列中会更容易吗?
BinaryBlob应该为您生成正确的VarBinary列。
Another way, using the "image" column type in mssql which dynamically allocates to fit very large files like pictures, here's an example. 另一种方式是在mssql中使用“ image”列类型 ,该类型动态分配以适合大型文件(如图片),这是一个示例。
The hbm.xml: hbm.xml:
<property name="Photo" column="Photo" type="BinaryBlob" not-null="true"></property>
The class property: 类属性:
private byte[] _photo;
public virtual byte[] Photo
{
get { return _photo; }
set { _photo = value; }
}
The Test, using a helper to get the nhibernate session: 测试,使用助手来获取nhibernate会话:
Image image = Image.FromFile(@"C:\Documents and Settings\someuser\Desktop\logoTop.gif");
byte[] imageByte;
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Gif);
imageByte = ms.ToArray();
}
NHSession sessionManager = new NHSession();
using (ISession session = sessionManager.GetSession())
using (ITransaction tx = session.BeginTransaction())
try
{
MyPhoto photo = new MyPhoto();
photo.Photo = imageByte;
session.Save(photo);
session.Refresh(photo);
Console.WriteLine(photo.EverifyPhotoId);
tx.Commit();
}
catch (HibernateException)
{
if (tx.IsActive)
tx.Rollback();
throw;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.