2

I'm new to Fluent NHibernate and C#.NET and struggling with this problem.

I have two tables:

audit: audit_seq (Primary Key), user_code (Foreign Key), audit_date

username: user_code (Primary Key), user_name

The audit table contains audit records with a foreign key field (user_code) for the user. The problem is that some of the user records have been deleted, but the audit records for those users remain (so I have orphaned Foreign Keys in the audit table). What I want is a result set with audit_seq, audit_date and user_name (but if orphaned the user_name should be blank).

I am using the following mapping, but believe that I need to change the UserName reference to create an outer join. I am not sure how to do that.

public class AuditMap : ClassMap<Audit>
{
    public AuditMap()
    {
        Id(x => x.AuditSeq).Column("audit_seq").GeneratedBy.Assigned();
        Map(x => x.AuditDate).Column("audit_date");
        References(x => x.UserName).Column("user_code");
    }
}

1 Answer 1

3

The table username should be mapped to an Entity (class UserName? I will use the User to distinguish its property UserName). Then it could be used in the Audit as a reference. In C#

public class Audit
{
  ...
  public virtual User User { get; set; }
  public virtual string UserName
  {
    get { return User != null ? User.UserName : string.Empty ;}
  }
}

The User mapping

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.UserCode).Column("user_code").GeneratedBy.Assigned();
        Map(x => x.UserName).Column("user_name");
        ...
    }
}

Then we can adjust the Audit mapping this way:

public class AuditMap : ClassMap<Audit>
{
    public AuditMap()
    {
        Id(x => x.AuditSeq).Column("audit_seq").GeneratedBy.Assigned();
        Map(x => x.AuditDate).Column("audit_date");
        References(x => x.User).Column("user_code")
             .NotFound.Ignore();
    }
}

so now we have Audit having reference to User. It will ignore the fact that some referenced Users are missing (.NotFound.Ignore()). And if there is any, our UserName property will return its name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.