How do I map to get a value from a primary table in Nhibernate?

I am facing a problem when I try to get a value from a primary table in a mapping file.

My tables:

CREATE TABLE Customer
(
    [CustomerId] INT PRIMARY KEY,
    [FullName] NVARCHAR(50) NOT NULL
)

CREATE TABLE CustomerOrder
(
    [CustomerOrderId] INT PRIMARY KEY,
    [CustomerId] INT,
    [TransactionDate] DATETIME
)

      

My classes:

public class CustomerOrder
{
    public class Id {get; set;}
    public class CustomerName {get; set;}
    public class TransactionDate {get; set;}
}
...

      

How do I get the FullName value and map the CustomerName property in my CustomerOrder interface mapping class?

0


source to share


2 answers


You really wouldn't. The best option would be to have a Customer property, which is an instance of the Customer class.

public class CustomerOrder
{
  public int Id { get; set; }
  public Customer Customer { get; set; }
}

public class CustomerOrderMap : ClassMap<CustomerOrder>
{
  public CustomerOrderMap()
  {
    Id(x => x.Id);
    References(x => x.Customer);
  }
}

      

Which you can use like this:



customerOrder.Customer.FullName

      

If you really want to have a property CustomerName

, you can create a delegate property on CustomerOrder

.

public string CustomerName
{
  get { return Customer.FullName; }
}

      

+1


source


If you want to map a class to multiple tables using Fluent-NHibernate, you can use the "WithTable" method.



    public CustomerOrderMap()
    {
        Id(x => x.Id);
        Map(x => x.TransactionDate);

        WithTable("Customer", m =>
        {
            // Use .TheColumnNameIs since the property name is different from the column name
            m.Map(x => x.CustomerName)
                .TheColumnNameIs("FullName");
        });
    }

      

0


source







All Articles