Search code examples
c#nhibernatenhibernate-mapping

Flattening an nested object into a single row in NHidernate


I've got one class nested in another:

public class InnerClass
{
    public string InnerProp1 { get; set; }
    public string InnerProp2 { get; set; }
}

public class OuterClass
{
    public string OuterProp1 { get; set; }
    public string OuterProp2 { get; set; }
    public InnerObject InnerClass { get; set; }
}

And I want to map it to this table:

CREATE TABLE FlatTable
(
    OuterProp1 VARCHAR(20),
    OuterProp2 VARCHAR(20),
    InnerProp1 VARCHAR(20),
    InnerProp2 VARCHAR(20),
)

I've tried a naive mapping

Property(x => x.OuterProp1);
Property(x => x.OuterProp2);
Property(x => x.InnerObject.InnerProp1);
Property(x => x.InnerObject.InnerProp2);

And this fails with a ArgumentNullException which I suspect is due to the x.InnerObject being null.

How can I create this mapping?


Solution

  • Using components

    Property(x => x.OuterProp1);
    Property(x => x.OuterProp2);
    Component(
        x => x.InnerClass,
        comp =>
        {
            comp.Property(x => x.InnerProp1);
            comp.Property(x => x.InnerProp2);
        });