Pierre-Alain Vigeant
Pierre-Alain Vigeant

Reputation: 23103

How to have two mapping for the same table in Fluent nHibernate?

I have a User table defined like this:

CREATE TABLE Users(
    UserId int IDENTITY(1,1) NOT NULL,
    UserName varchar(128) NOT NULL,
    Name nvarchar(200) NOT NULL,
    Password binary(64) NOT NULL,
    PasswordSalt binary(16) NOT NULL
)

I'm trying to have two class that map to this table:

The idea behind this is that SecurityUser is a internal object that require a intermediate service to modify the password. This is needed to avoid returning the password and salt everytime I need to query a user.

The User class is, what I call, a safe object that doesn't provide any user sensitive information.

Right now, I have defined two map:

public class UserMap : ClassMap<User>
{
    protected UserMap()
    {
        Id(x => x.Id);
        Map(x => x.UserName);
        Map(x => x.Name);
    }
}

and

public class SecurityUserMap : SubclassMap<SecurityUser>
{
    protected SecurityUserMap()
    {
        Map(x => x.Password);
        Map(x => x.PasswordSalt);
        Table("Users");
    }
}

The problem is that nHibernate creates a table called SecurityUser. I tried using the Table("Users") function to specify the same table, but I then get a invalid nhibernate mapping.

How can I achieve what I am trying to do? Or is there is an alternate approach?

Upvotes: 0

Views: 965

Answers (1)

Paco
Paco

Reputation: 8381

NHibernate does not know when to save a User and when to save a security user. You need something in your database to tell NHibernate when a record is a user, and when it is a security user. To tell you how do to that, I need to know why "This is needed to avoid returning the password and salt everytime I need to query a user."? When the reason is performance, You can probably not measure the difference. If you use the User class for reporting scenario's, you can better use a projection class to select the result of the reporting queries to, than a mapped entity.

Upvotes: 1

Related Questions