2009-04-08 20 views
2

我的数据库看起来财产以后这样的:nhibernate:如何映射引用enity的组件?

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)?

回答

1

我也不确定从组件中引用实体是怎么做的。我自己也是这样做的(与一个国家实体一样)。

至于映射,这是非常简单的:

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); 
    } 
} 

有时候,我要做的就是添加静态类的组件,使类映射更好一点:

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 
     }; 
    } 
} 

在这case ColumnName是一个简单的函数,它将前缀附加到列名称上(这在我可以使用的美妙的遗留数据库中非常方便)。

然后在类映射你只是做:

Component<Name>(x => x.Name, c => NameMap.AsComponent("prefix")); 
+0

OO,我喜欢更流畅成分的语法!我不确定我是否可以从组件中引用。感谢您验证我可以。那么引用你的国家实体呢?或者你最终改变了它? – 2009-04-08 16:38:46