Pawel Krakowiak
Pawel Krakowiak

Reputation: 10100

How to map a string property to a binary column in the database?

I have a class for a user entity. One of the properties is the user's password (a hash, actually). I made it a string (streamlined code):

public class User
{
    public virtual int Id { get; set; }
    public virtual string Password { get; set; }
}

There's also a Fluent NHibernate mapping (streamlined code):

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id).GeneratedBy.Sequence("users_id_seq");
        Map(x => x.Password); // what do I put here???
    }
}

The database column is of bytea data type on PostgreSQL. The above mapping doesn't work, because the property is string (text). What should I do?

Upvotes: 1

Views: 403

Answers (2)

Pawel Krakowiak
Pawel Krakowiak

Reputation: 10100

Here is the final solution which works both ways (read & write), what I tried earlier didn't work properly. Hope this will help somebody.

public class User
{
    private byte[] _password;

    public virtual int Id { get; private set; }

    public virtual string Password
    { 
        get { return System.Text.Encoding.Unicode.GetString(_password); }
        set { _password = System.Text.Encoding.Unicode.GetBytes(value); }
    }
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id).GeneratedBy.Sequence("users_id_seq");
        Map(x => x.Password)
            .Access.LowerCaseField(Prefix.Underscore)
            .CustomType<byte[]>();
    }
}

Upvotes: 0

J. Ed
J. Ed

Reputation: 6752

you can Make Password a public property, which is only used to reference to the underlying private property HashedPassword.
something like so:
protected virtual byte[] /*or whatever the type is*/ HashedPassword {get; set;} public virtual string Password
get
{
return (string)(HashedPassword); //or however you want to cast it to string...
}
set
//...

you can then tell fluent nHib to ignore your Password property.

Upvotes: 1

Related Questions