Reputation: 14145
I have following model
public class Car : Entity<int>
{
public virtual int Id{ get; set; }
...
public virtual Engine Engine { get; set; }
}
and I'm using 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?
}
}
how map Engine in this CarMap object?
Upvotes: 0
Views: 4315
Reputation: 6520
You need a little more information in the question, but here's a couple of options.
Is this really a one to one relationship? One to one relationships are somewhat unique in that both sides of the relationship tend to share the same Id. Like David Osborne said you most likely want a One to Many relationship. But you you want it to be bi-directional? i.e. you can navigate down from the Engine to all the cars that may have that engine or up from the car to a specific engine. i.e. engine is Chrysler Hemi engine 5.7L and it is in the cars, Ram Pickup, Dodge Durango, Dodge Charger.
Then you may want to map the objects like this
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; }
}
So if you are mapping the Engine you need to define the Cars mapping list this
Bag(x => x.Cars, map =>
{
map.Key(k => k.Column(col => col.Name("EngineId")));
map.Cascade(Cascade.All | Cascade.DeleteOrphans); //optional
},
action => action.OneToMany());
and the other side of the relationship like this
ManyToOne(x => x.Engine, map =>
{
map.Column("EngineId");
map.NotNullable(true); // if you require the Engine to be in a car
});
If you just want a one way mapping from the car to the engine, just remove all the references to the Cars list and delete the Bag mapping.
Upvotes: 1
Reputation: 6791
Using Fluent NH, I would use References()
, which has a mapping-by-code equivalent of ManyToOne()
apparently.
Upvotes: 0