我的数据库看起来像这样:
MyEntity State
----- -----
id id
street name
stateId ...
zip
status
...
我的模型看起来像这样:
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; }
// ...
}
我对引用实体的地址组件有点不舒服。闻起来像一个糟糕的模型。是吗?如果没有,我将如何映射(最好使用流畅的 nhibernate)?
最佳答案
我也不确定如何从组件中引用实体。我自己已经这样做了(与一个国家实体,不少)。
至于映射,它非常简单:
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);
}
}
有时我所做的是为组件添加一个静态类,以使 ClassMap 更好一点:
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
};
}
}
在这种情况下,ColumnName 是一个简单的函数,它将前缀附加到列名(这在我使用的美妙的遗留数据库中非常方便)。
然后在 ClassMap 中,您只需执行以下操作:
Component<Name>(x => x.Name, c => NameMap.AsComponent("prefix"));
关于nhibernate:如何映射引用实体的组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/730220/