Fluent NHibernate Automappings generating 2 foreign keys for 1 relationship

跟風遠走 提交于 2019-12-12 04:59:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!