使用 NHibernate 与 EAV 数据模型

15

我试图利用NH映射到一个宽松解释的EAV/CR数据模型。

我已经完成了大部分工作,但在映射实体属性集合时遇到了困难。

这是相关的表:

--------------------
| Entities         |
--------------------
| EntityId  PK     |-|
| EntityType       | |
-------------------- |
         -------------
         |
         V
--------------------
| EntityAttributes |    ------------------    ---------------------------
--------------------    | Attributes     |    | StringAttributes        |
| EntityId  PK,FK  |    ------------------    ---------------------------
| AttributeId  FK  | -> | AttributeId PK | -> | StringAttributeId PK,FK |
| AttributeValue   |    | AttributeType  |    | AttributeName           |
--------------------    ------------------    ---------------------------

AttributeValue列被实现为sql_variant列,我已经为其实现了一个NHibernate.UserTypes.IUserType。

我可以创建一个EntityAttribute实体并直接持久化它,以便该层次结构的一部分正在工作。

我只是不确定如何将EntityAttributes集合映射到Entity实体。

请注意,EntityAttributes表可能(并且确实)包含给定EntityId / AttributeId组合的多行:

EntityId AttributeId AttributeValue
-------- ----------- --------------
1        1           Blue
1        1           Green

这个例子中,StringAttributes 行看起来像这样:

StringAttributeId AttributeName
----------------- --------------
1                 FavoriteColor

我该如何有效地将这个数据模型映射到我的实体域中,以便Entity.Attributes("FavoriteColors")返回一个收藏夹颜色的集合?类型为System.String?


如果您计划通过属性值查找实体,我不确定 sql_variant 是否正常工作。您应该尝试这个。 - Stefan Steinegger
1个回答

1

在这里

class Entity
{
    public virtual int Id { get; set; }

    internal protected virtual ICollection<EntityAttribute> AttributesInternal { get; set; }

    public IEnumerable<T> Attributes<T>(string attributeName)
    {
        return AttributesInternal
            .Where(x => x.Attribute.Name == attributeName)
            .Select(x => x.Value)
            .Cast<T>();
    }
}

class EntityAttribute
{
    public virtual Attribute Attribute { get; set; }

    public virtual object Value { get; set; }
}

class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        HasMany(e => e.AttributesInternal)
            .Table("EntityAttributes")
            .KeyColumn("EntityId")
            // EntityAttribute cant be an Entity because there is no real Primary Key
            // (EntityId, [AttributeId] is not unique)
            .Component(c =>
            {
                c.References(ea => ea.Attribute, "AttributeId").Not.LazyLoad();
                c.Map(ea => ea.Value, "AttributeValue").CustomType<VariantUserType>();
            });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接