简体   繁体   中英

Mapping Fluent NHibernate where the primary key should also be a foreign key

I have a user object like so:

public class User
{
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    ...
}

this is fluently mapped in nhibernate:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.UserId).Column("UserId");
        Map(x => x.UserName).Not.Nullable();
        ...
    }
}

I'm trying to build a credential block that is separate from the user object, so the password and salt are not carried around in the user class like so:

public class UserCredential
{
    public User User { get; set; }
    public byte[] Password { get; set; }
    public string Salt { get; set; }
}

...but I cannot figure out how to properly map this. Ultimately, in the database, I would expect to see a UserId column in the UserCredentials table, that is both a primary key and a foreign key to the Users table. The Users table should have no reference to the UserCredentials table. How would I write that ClassMap<UserCredential> class?

This seems to be a one-to-one relationship and would therefore be mapped using HasOne in FNH.

Example

    public UserCredentialMap()
    {
        Id(x => x.Id)
            .Column("UserId")
            .GeneratedBy.Foreign("User");

        HasOne(x => x.User).Constrained();
    }

You may be able to map it like this as well:

public UserCredentialMap()
{
    Id(x => x.Id, "UserId");

    References(x => x.User, "UserId")
            .Not.Update()
            .Not.Insert();
}

As you don't want to give the Credentials it's own primary key, it seems to me that what you really want is a Component ( more details ).

This will mean that the Credential data is stored in the same table as the User data, but is modelled in your domain as a separate object which is a property of your User class.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM