问题
I have this setup (condensed for brevity)
Class Employee
virtual IList<ChecklistItem> HasInitialed { get; private set; }
Class ChecklistItem
virtual Employee InitialedBy { get; set; }
When this is generated I get these tables
Employee
Id
ChecklistItem
Id
InitialedBy_id <----
Employee_id <----
The ChecklistItem has 2 foreign keys for Employee, I'm assuming Employee_id to map ChecklistItem.Employee and InitialedBy_id to map ChecklistItem.InitialedBy. How can I tell NHibernate that this is the same bidirectional relationship and only requires 1 foreign key?
I'm kind of new to NHibernate in general, but this seems like it should be pretty standard.
This is what I've come up with when I'm configuring my database to generate the right schema, is it right?
.Override<Employee>(map => map
.HasMany<ChecklistItem>(x => x.HasInitialed)
.KeyColumn("InitialedBy_id"))
If that is right, is there a way to choose KeyColumn based on the ChecklistItem's property name (a lambda)?
回答1:
as a convention for all hasmanies
class HasManyConvention : IHasManyConvention
{
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Key.Column(((ICollectionInspector)instance).Name + "_id");
}
}
or only for this
class HasManyConvention : IHasManyConvention, IHasManyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IOneToManyCollectionInspector> criteria)
{
criteria.Expect(x => x.Name == "HasInitialed"); // and/or entity type
}
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Key.Column(((ICollectionInspector)instance).Name + "_id");
}
}
convention for Manytoone/References
class ReferenceConvention : IReferenceConvention
{
public void Apply(IManyToOneInstance instance)
{
instance.Column(instance.Name + "_id");
}
}
来源:https://stackoverflow.com/questions/7515785/fluent-nhibernate-automappings-generating-2-foreign-keys-for-1-relationship