views:

248

answers:

1

My db looks somthing like this:

MyEntity     State
-----        -----
id           id
street       name
stateId      ...
zip
status
...

My Model looks like this:

class MyEntity
{
     int id { get; set; }
     Address location { get; set; }
     string status { get; set; }
     // ...
}

class Address
{
    string street { get; set; }
    string zip { get; set; }
    State state { get; set; }
    // ...
}

class State
{
    int id { get; set; }
    string name { get; set; }
    // ...
}

I'm a little uncomfortable with my address component referencing an entity. Smells like a poor model. Is it? If not, how would I map this (preferably with fluent nhibernate)?

+1  A: 

I'm also unsure of what to make of referencing an entity from a component. I've done so myself (with a State entity, no less).

As far as the mapping, it's pretty straightforward:

public class MyEntityMap : ClassMap<MyEntity>
{
    public MyEntityMap()
    {
        Id(x => x.id);
        Component<Address>(x => x.location, c =>
        {
            c.Map(x => x.street);
            c.Map(x => x.zip);
            c.References<State>(x => x.state);
        });
        Map(x => x.status);
    }
}

Sometimes what I do is add a static class for the component to make the ClassMap a little nicer:

public static class NameMap
{
    public static Action<ComponentPart<Name>> AsComponent(string prefix)
    {
        return c =>
        {
            c.Map(x => x.Title, ColumnName(prefix, "Title"));
            // and so on
        };
    }
}

In this case ColumnName is a simple function that attaches the prefix to the column name (which is pretty handy in the wonderful legacy DBs I get to play in).

Then in the ClassMap you just do:

Component<Name>(x => x.Name, c => NameMap.AsComponent("prefix"));
Stuart Childs
oo, I like the more fluent component syntax! wasn't sure if I could reference from a component. Thanks for verifying I can. Referencing your state entity worked out then? Or did you end up changing it?
TheDeeno
Yes, it works as-is. The way I see it, the appropriate model is for Address to be a separate entity in which case having a relationship between Address and State is fine. However, with legacy DBs, I don't have the option to restructure so I have to focus on what can be done and not what is "right".
Stuart Childs