2017-02-10 291 views
0

我有以下型号NHibernate的映射,映射对象

public class Car : Entity<int> 
{ 
    public virtual int Id{ get; set; } 
    ... 
    public virtual Engine Engine { get; set; } 

} 

,我使用nhibernate mapping by code approach

public class CarMap : ClassMapping<Car> 
{ 
    public CarMap() 
    { 
     Id(x => CarId, m => m.Generator(Generators.Identity)); 
     // how map reference Engine? 
     **// edit** 
     HasOne(x=>x.Engine, m=>{}) // is this good enough? 

    } 
} 

如何在此地图引擎CarMap对象?

回答

0

用流利的NH,我会用References(),其中有ManyToOne()显然是一个mapping-by-code equivalent

+0

你确定它是ManyToOne不OneToOne? – user1765862

+0

我没有使用映射代码,我只是继续讨论链接的文章所说的内容。它从2012年开始,所以事情可能已经改变...... –

+0

谢谢....,。,,, – user1765862

1

你需要更多的信息,但这里有几个选项。

这真的是一对一的关系吗?一对一的关系在某种程度上是独一无二的,因为双方的关系倾向于共享同一个Id。就像大卫奥斯本说,你很可能想要一对多的关系。但是你希望它是双向的?即,您可以从引擎向下导航到所有可能具有该引擎的汽车或从汽车上升到特定引擎的汽车。即发动机是克莱斯勒Hemi发动机5.7L,在汽车,Ram Pickup,道奇Durango,道奇Charger。

那么你可能想映射这样

public class Engine : Entity<int> 
{ 
    public Engine() 
    { 
     Cars = new List<Car>(); 
    } 

    public virtual int Id { get; protected set; } 
    public virtual decimal Displacement { get; set; } 
    //more properties 

    public virtual IList<Car> Cars { get; } 

    public virtual void AddCar(Car car) 
    { 
     if (Cars.Contains(car)) return; 

     Cars.Add(car); 
    } 

    public virtual void RemoveCar(Car car) 
    { 
     if (!Cars.Contains(car)) return; 

     Cars.Remove(car); 
    } 
} 

public class Car : Entity<int> 
{ 
    public virtual int Id { get; set; } 
    public virtual Engine Engine { get; set; } 

} 

的对象,因此,如果您正在映射,你需要定义汽车映射列表中的引擎这个

 Bag(x => x.Cars, map => 
     { 
      map.Key(k => k.Column(col => col.Name("EngineId"))); 
      map.Cascade(Cascade.All | Cascade.DeleteOrphans); //optional 
     }, 
      action => action.OneToMany()); 

和的另一面像这样的关系

 ManyToOne(x => x.Engine, map => 
     { 
      map.Column("EngineId"); 
      map.NotNullable(true); // if you require the Engine to be in a car 
     }); 

如果你只是想从汽车的单向映射到en gine,只需删除对Cars列表的所有引用并删除Bag映射。