MichaelGG
MichaelGG

Reputation: 10006

NHibernate: Map same class to multiple tables depending on parent

I have a model where multiple classes have a list of value types:

class Foo { public List<ValType> Vals; }
class Bar { public List<ValType> Vals; }

Foo and Bar are unrelated apart from that they both contain these vals. The rules for adding, removing, etc. the ValTypes are different for each class. I'd like to keep this design in my code.

There are times when I want to copy some Vals from a Foo to a Bar, for example. In the database, each ValType has its own table, to keep it small, light (it just has the parent ID + 2 fields), and allow integrity checks. I know NHibernate says I should keep my objects as granular as the database, but that just makes my code uglier.

The best I've thought of so far is to make separate subclasses of ValType, one for each parent. Then I can map those at that level. Then, I'll hook up add and remove logic to auto-convert between the right subclasses, and actually store them in a private list that has the right subclass type. But this seemed a bit convoluted.

How can I map this in NHibernate (Fluent NHibernate if possible)?

Please let me know if this is a duplicate -- I'm not quite sure how to search this.

Upvotes: 2

Views: 3652

Answers (2)

user29439
user29439

Reputation:

You can find an example on the Google Code page for Fluent NHibernate.

Model

public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
}

Schema

table Customer (
    Id int primary key
    Name varchar(100)
)

table CustomerAddress (
    CustomerID int,
    Address varchar(100)
)

Mapping

public class CustomerMap : ClassMap<Customer>
{
    public CustomerMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);

        WithTable("CustomerAddress", m =>
        {
            m.Map(x => x.Address);
        });
    }
}

In this example, an entity is split across two tables in the database. These tables are joined by a one-to-one on their keys. Using the WithTable feature, you can tell NHibernate to treat these two tables as one entity.

Upvotes: 2

Aleris
Aleris

Reputation: 8069

At database level a solution would be to have:

Val(Id)
Bar(Id)
BarToVal(IdBar, IdVal)
FooToVal(IdFoo, IdVal) 

I am not very sure how would these be mapped. Maybe something like:

// BarMap:  
HasManyToMany(x => x.Vals).WithTableName("BarToVal");

// FooMap:  
HasManyToMany(x => x.Vals).WithTableName("FooToVal");

Hope it's making sense...

Upvotes: 3

Related Questions