How to map NHibernate custom collection with fluen

2019-04-13 19:14发布

I am trying to map the collection for two days without success. I also read all possible articles and forums but still down there. Ok, here is the problem:

1) The collection class contains a private field "_internalCollection" which is mapped with NHib.

2) The holding entity should expose the collection trough readonly property.

3) I want to avoid implementing NHibernate interface IUserCollectionType!!!

I did this with xml mapping and it work great. The WarehouseEntity is a collection Item. Warehouses is a readonly property in OrgEntity class.

  <component name="Warehouses" class="Core.Domain.Collections.EntitySet`1[Core.Domain.OrgStructure.IWarehouseEntity,Core],Core">
    <set name="_internalCollection" table="`WAREHOUSE`" cascade="save-update" access="field" generic="true" lazy="true" >
      <key column="`WarehouseOrgId`" foreign-key="FK_OrgWarehouse" />
      <!--This is used to set the type of the collection items-->
      <one-to-many class="Domain.Model.OrgStructure.WarehouseEntity,Domain"/>
    </set>
  </component>

Any idea how can I do it with fluent NHibernate?

EDIT: Core.Domain.Collections.EntitySet`1 is base collection class. It provides basic functionality for working with collections and can fit any class which is IEntity interface.

1条回答
乱世女痞
2楼-- · 2019-04-13 19:45

Try:

HasMany(x => x.Warehouses)
    .AsSet().KeyColumn("WarehouseOrgId")
    .Access.CamelCaseField(Prefix.Underscore)
    .ForeignKeyConstraintName("FK_OrgWarehouse");

Edit: I missed a key part of the question so here's another try:

Component(x => x.Warehouses, m =>
    {
        m.HasMany<Warehouse>(Reveal.Member<EntitySet<IWarehouseEntity>>("_internalCollection")
           .AsSet().KeyColumn("WarehouseOrgId")
           .ForeignKeyConstraintName("FK_OrgWarehouse");
    });

I'm sure that's not it but hopefully it puts you on the right path. Also have a look using ComponentMap.

My advice is to avoid custom collections entirely. I replaced all of ours with extension methods on IEnumerable<T>.

查看更多
登录 后发表回答