我想使用Nhibernate和Conform到MSSQL 2008来保存文件。
我找到了文章如何做到并实现一切。 http://harmonypsa.blogspot.com/2013/07/using-filestream-with-sql-server-and.html
当我运行我的代码时,我得到异常:“byte []值的长度超过映射/参数中配置的长度。” 这是我的班级:
public class BaseEntity
{
public virtual int Id { get; set; }
}
public class TestEntity : BaseEntity
{
public virtual Guid ImageId { get; set; }
public virtual Binary Image { get; set; }
}
我的映射:
class Program
{
static void Main(string[] args)
{
var factory = BuildFactory();
using (ISession session = factory.OpenSession())
{
using (ITransaction tx = session.BeginTransaction())
{
using (FileStream fi = File.OpenRead(@"C:\A\2013-10-31_1633.png"))
{
var photoBytes = new byte[fi.Length];
fi.Read(photoBytes, 0, photoBytes.Length);
var te = new TestEntity { Image = photoBytes };
session.SaveOrUpdate(te);
tx.Commit();
}
}
}
}
internal static Configuration GetConfiguration()
{
DomainMapper mapper = new DomainMapper();
HbmMapping generatedMappigs = mapper.GenerateMappigs();
var cfg = new Configuration();
cfg.SessionFactory().Proxy.Through<NHibernate.Bytecode.DefaultProxyFactoryFactory>().Integrate.Using<MsSql2008Dialect>()
.AutoQuoteKeywords().Connected.By<SqlClientDriver>().ByAppConfing("DBConnectionString").CreateCommands
.ConvertingExceptionsThrough<SQLStateConverter>();
cfg.SetProperty("show_sql", "true");
cfg.SetProperty("format_sql", "true");
cfg.AddDeserializedMapping(generatedMappigs, string.Empty);
new SchemaUpdate(cfg).Execute(true, true);
return cfg;
}
private static ISessionFactory BuildFactory()
{
Configuration cfg = GetConfiguration();
return cfg.BuildSessionFactory();
}
public HbmMapping GenerateMappigs()
{
IEnumerable<Type> domainEntities = this.GetDomainEntities();
ObjectRelationalMapper relationalMapper = new ObjectRelationalMapper();
relationalMapper.TablePerConcreteClass(domainEntities);
Mapper mapper = new Mapper(relationalMapper);
HbmMapping mapping = mapper.CompileMappingFor(domainEntities);
//File.WriteAllText(@"d:\mappings.xml", Serialize(mapping));
return mapping;
}
/// <summary>
/// Gets all objects that are inherited from EntityBase.
/// </summary>
private IEnumerable<Type> GetDomainEntities()
{
Assembly domainAssembly = typeof(BaseEntity).Assembly;
IEnumerable<Type> domainEntities = from t in domainAssembly.GetTypes()
where t.BaseType == typeof(BaseEntity) && !t.IsGenericType
select t;
return domainEntities;
}
}
有什么想法吗?
答案 0 :(得分:3)
在Document.hbm.xml文件中,
<property name="Image" type="System.Drawing.Image, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<column name="Image" length="2147483647" not-null="false" />
</property>
表中的Image列是MySQL Server 2008 Express数据库中的varbinary(MAX)类型,我使用的是MsSql2008方言。
答案 1 :(得分:1)
我已更新此代码: 公共类TestEntity:BaseEntity { public virtual Guid ImageId {get;组; }
public virtual System.Byte[] Image { get; set; }
}
并将此字符串添加到映射器中:
mapper.Class<TestEntity>(map => map.Property(o => o.Image, pm => pm.Type(NHibernateUtil.BinaryBlob)));