Comparing Byte Arrays with NHibernate

The following Linq to NHibernate query results in System.NotSupportedException.

IEnumerable<File> FindByMd5(byte[] md5)
{
    return this.Session.Query<File>().Where(f => f.Md5.SequenceEqual(md5)).ToList();
}

How do I do this using Linq for NHibernate or QueryOver<File>()?

+3
source share
3 answers

Due to the fact that the error already indicates that NHibernate does not support this function. I would create a named query and resolve the equation in the query. I tested it using MySQL (using the example of sharing the username and password as an example), and the following statement returns the desired string (password is the BINARY field (32)):

SELECT * FROM `user` WHERE `password` = MD5('test');

Using MSSQL, you can:

SELECT * FROM [user] WHERE [password] = HASHBYTES('MD5', 'test')

, , .hbm.xml, "User.hbm.xml", :

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="My.Model" namespace="My.Model">
  <sql-query name="GetUserByCredentials">
    <return class="My.Model.User, My.Model" />
    <![CDATA[
      SELECT * FROM User WHERE Username = :Username AND Password = MD5(:Password)
    ]]>
  </sql-query>
</hibernate-mapping>

, Fluent NHibernate, - NHibernate:

Fluently.Configure()
    .Database(MySqlConfiguration.Standard
        .ConnectionString(x => x.FromConnectionStringWithKey("Test"))
        .AdoNetBatchSize(50))
    .Cache(c => c
        .UseQueryCache()
        .ProviderClass<HashtableCacheProvider>())
    .Mappings(m =>
    {
        m.FluentMappings.AddFromAssemblyOf<IHaveFluentNHibernateMappings>().Conventions.Add(ForeignKey.EndsWith("Id"));
        m.HbmMappings.AddFromAssemblyOf<IHaveFluentNHibernateMappings>();
    })
    .BuildConfiguration();

".hbm.xml" "IHaveFluentNHibernateMappings"

:

public User GetUserByCredentials(string username, string password)
{
    IQuery query = Session.GetNamedQuery("GetUserByCredentials");
    query.SetParameter("Username", username);
    query.SetParameter("Password", password);

    return query.UniqueResult<User>();
}

GetUserByCredentials, .

, - , MD5 :

System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in md5ByteArray)
{
   s.Append(b.ToString("x2").ToLower());
}
password = s.ToString();

!

+1

Ive , MD5 .

public class PersistedFile
{
    public virtual int Id { get; set; }
    public virtual string Path { get; set; }
    public virtual string Md5 { get; set; }
}

:

public PersistedFile Save(string filePath)
{
    using (var fileStream = new FileStream(filePath, FileMode.Open))
    {
        var bytes = MD5.Create().ComputeHash(fileStream);

        using (var transaction = this.Session.BeginTransaction())
        {
            var newFile = new PersistedFile
            {
                Md5 = BitConverter.ToString(bytes),
                Path = filePath,
            };
            this.Session.Save(newFile);
            transaction.Commit();
            return newFile;
        }
    }
}

:

public IEnumerable<PersistedFile> FindByMd5(string md5)
{
    using (var transaction = this.Session.BeginTransaction())
    {
        var files = this.Session.Query<PersistedFile>().Where(f => f.Md5 == md5).ToList();
        transaction.Commit();
        return files;
    }
}
0

Old Q, but still a problem with Linq. Thus, using NHibernate and SQLite, when comparing with the byte value of an array, you can use a query with restrictions or criteria.

session.QueryOver<TestItem>().WhereRestrictionOn(i => i.Foo).IsBetween(aaa).And(aaa);

or

session.CreateCriteria<TestItem>().Add(Restrictions.Eq("Foo", aaa))
0
source

All Articles