[英]What is the best way to store byte array in SQL database using NHibernate?
我的C#類中有一個字節數組,需要使用NHibernate將其持久化到SQL Server 2005數據庫中。 我應該為該列使用哪種SQL數據類型,以及如何使用NHiberante為我執行持久性? 如果答案是自定義NHibernate類型,是否有示例代碼在附近這樣做?
將字節數組轉換為字符串並將其保存在varcahr列中會更容易嗎?
BinaryBlob應該為您生成正確的VarBinary列。
另一種方式是在mssql中使用“ image”列類型 ,該類型動態分配以適合大型文件(如圖片),這是一個示例。
hbm.xml:
<property name="Photo" column="Photo" type="BinaryBlob" not-null="true"></property>
類屬性:
private byte[] _photo;
public virtual byte[] Photo
{
get { return _photo; }
set { _photo = value; }
}
測試,使用助手來獲取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.