Mapping to Single Entity when having Many relationsship

Martin F's Avatar

Martin F

20 Jun, 2010 10:33 PM via web

Hello,

i have 2 entities - Member and Email, which have corresponding tables (Members and Emails)

The Emails table contains the following columns - Id, MemberId, ValidationCode, Address, CreatedAt, ValidatedAt

If a user wants to change his Email address a new row is inserted into the Emails table, and when Validated (ValidatedAt is set to the current date), it should become "active" and available through the Member entity.

Basically the Member entity should hold a reference to the most recent validated Email.

But how can i map this ?

I dont want a List property with all Emails relating to the Member, but only 1 Email entity - which is found by the most recent validated email (validatedAt not null and order by ValidatedAt)

Martin :)

  1. 2 Posted by Martin on 25 Jun, 2010 12:10 PM

    Martin's Avatar

    Anyone have an idea of how it can be done ?

    The table structure looks like this

    Members

    Id
    FirstName
    LastName

    Emails

    Id
    Address
    ValidationCode
    ValidatedAt
    MemberId

    My entities looks something like this

    public class Member
    {
        public virtual Email Email { get; set; }
    
        public virtual String FirstName { get; set; }
        public virtual String LastName { get; set; }
    }
    
    public class Email
    {
        public virtual Member Member { get; set; }
    
        public virtual String Address { get; set; }
        public virtual String ValidationCode { get; set; }
        public virtual DateTime ValidatedAt { get; set; }
    }
    

    I want the Email property on Member to map to an instance of Email where ValidatedAt is not null and ordered by ValidatedAt (so the most recent validated email is mapped).

  2. Support Staff 3 Posted by Paul Batum on 28 Jun, 2010 10:59 AM

    Paul Batum's Avatar

    The best option I can think of is to use a one-to-many of emails, make it
    private, map it with a where clause like:

      .Where("EmailID IN (SELECT TOP 1 EmailID FROM Email Where Email.MemberID =
    _memberid ORDER BY ValidatedAt Desc)");

    and then publicly expose the returned email in the list as a single
    reference.

    Have you tried asking on the nhibernate
    users<http://groups.google.com/group/nhusers/> mailing
    list? Your question is more about NH usage than the FNH mappings.

    (I haven't tested the above SQL, but I think something like that should
    work)

Reply to this discussion

Preview Comments are parsed with Markdown. Help with syntax

Attached Files

    You can attach files up to 10MB

    What comes next? 'Monday Tuesday Wednesday ?????'