简体   繁体   中英

How to include records from 2 db tables into a single view using NHibernate / Fluent NHibernate?

I'm new to NHibernate / Fluent NHibernate (started with it this weekend) and I'm having difficulties solving the following.

I have 2 SQL Server tables:

[Client]

ID        INT          NOT NULL IDENTITY(1,1)
Name      VARCHAR(100) NOT NULL
Email     VARCHAR(255) NOT NULL
BirthDate DATE

[Phones]

ID       INT         NOT NULL IDENTITY(1,1)
Number   VARCHAR(14)
Category INT
ClientID INT         NOT NULL     
         FOREIGN KEY REFERENCES [Client](ID),

POCO classes:

public class Clients
{
    public virtual int ID { get; set; }
    public virtual string Name { get; set; }
    public virtual string Email { get; set; }
    public virtual DateTime BirthDate { get; set; }
    public virtual Phones Phones { get; set; }
}

public class Phones
{
    public virtual int ID { get; set; }
    public virtual string Number { get; set; }
    public virtual PhoneCategory.PCategory Category { get; set; }
    public virtual Clients Client { get; set; }
}

public static class PhoneCategory
{
    public enum PCategory
    {
        Personal,
        Comercial,
        Residential,
        Other
    }
}

Mappings:

public class ClientsMap : ClassMap<Clients>
{
    public ClientsMap()
    {
        Table("Clients");
        Id(x => x.ID);
        Map(x => x.Name);
        Map(x => x.Email);
        Map(x => x.BirthDate);
        References(x => x.Phones).Column("ClientID").Cascade.All();
    }
}

public class PhonesMap : ClassMap<Phones>
{
    public PhonesMap()
    {
        Table("Phones");
        Id(x => x.ID);
        Map(x => x.Number);
        Map(x => x.Category).CustomType<PhoneCategory.PCategory>();
    }
}

My view for the Clients class is working fine, I can save, update, list and delete. But how could I include the records of the Phones class?

Instead of the References(x => x.Phones).Column("ClientID").Cascade.All(); line in the ClientsMap , you need to use the HasMany() method.

Eg

HasMany(c => c.Phones)

Documentation here .

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