NHibernate按代码映射等价于<composite-index>的复合词典键</composite-index>

时间:2015-02-04 11:43:17

标签: c# nhibernate mapping-by-code

是否可以使用按代码映射来映射具有多列密钥的字典?我还没有找到相当于<composite-index>的内容。

示例实体:

public class Warehouse
{
    // ctors

    private IDictionary<StorageCoordinates, StoragePosition> _storagePositions;

    public virtual string Id { get;  protected set; }

    public virtual IEnumerable<StoragePosition> StoragePositions
    {
        get { return _storagePositions.Values; }
    }

    public virtual StoragePosition GetStoragePosition(StorageCoordinates coordinates)
    {
        return _storagePositions[coordinates];
    }
}

public class StoragePosition
{
    // ctors

    public virtual StorageCoordinates Coordinates { get; protected set; }

    public virtual bool IsOccupied { get; set; }
}

public struct StorageCoordinates
{
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}

使用XML,我可以像这样映射Warehouse._storagePositions

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Warehouse, Domain" table="Warehouse">
    <id name="Id" type="string" length="50" column="Id" />
    <map name="StoragePositions" access="field.camelcase-underscore" cascade="all-delete-orphan">
      <key column="Warehouse" />
      <composite-index class="StorageCoordinates, Domain">
        <key-property name="X" />
        <key-property name="Y" />
        <key-property name="Z" />
      </composite-index>
      <one-to-many class="StoragePosition, Domain" />
    </map>
  </class>
</hibernate-mapping>

我不确定是否以及如何将其转换为(顺从)代码映射。这是我走了多远:

class WarehouseMap : ClassMapping<Warehouse>
{
    public WarehouseMap()
    {
        Table("Warehouse");
        Id(x => x.Id, x => x.Column("Id"));
        Map<StorageCoordinates, StoragePosition>("_storagePositions",
            x =>
            {
                x.Cascade(Cascade.All | Cascade.DeleteOrphans);
                x.Key(k => k.Column(c => c.Name("Warehouse")));
            },
            x =>
            {
                x.Element(k => k.Columns
                (
                    c => c.Name("X"),
                    c => c.Name("Y"),
                    c => c.Name("Z"))
                );
            },
            x => x.OneToMany(m => m.Class(typeof(StoragePosition))));
    }
}

然而,这将产生MappingException

"Could not determine type for: StorageCoordinates, Domain, for columns: NHibernate.Mapping.Column(X), NHibernate.Mapping.Column(Y), NHibernate.Mapping.Column(Z)"

对此的任何见解将不胜感激!不幸的是,关于按代码映射的文档似乎不存在:-(。我尝试使用Fluent NHibernate,但是使用Dictionary映射似乎更糟糕。

1 个答案:

答案 0 :(得分:0)

似乎我得到了正确的映射 - 唯一的问题是StorageCoordinatesstruct。将其设为class后,映射就可以了。可能也不会使用XML映射。

更新:显然,根据代码映射,甚至根本不需要显式映射复合词典键。 NHibernate似乎以某种方式解决了问题。

就像我喜欢NHibernate一样,这里有更多的文档,那里会很好......