I have an array of bytes in my C# class, and need to persist it into a SQL Server 2005 database using NHibernate. What SQL data type should I use for the column, and how do I got about using NHiberante to do the persistance for me? If the answer is a custom NHibernate type, is there any sample code knicking around to do this?
Would it just be easier to convert the byte array to a string and persist it in a varcahr column?
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.
The 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:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.