将NHibernate与EAV数据模型结合使用
我试图利用NH映射到一个数据模型,该模型是EAV/CR数据模型的松散解释 我的大部分工作正常,但我正在努力映射Entity.Attributes集合 以下是相关表格:将NHibernate与EAV数据模型结合使用,nhibernate,nhibernate-mapping,entity-attribute-value,Nhibernate,Nhibernate Mapping,Entity Attribute Value,我试图利用NH映射到一个数据模型,该模型是EAV/CR数据模型的松散解释 我的大部分工作正常,但我正在努力映射Entity.Attributes集合 以下是相关表格: -------------------- | Entities | -------------------- | EntityId PK |-| | EntityType | | -------------------- | ------------- |
--------------------
| Entities |
--------------------
| EntityId PK |-|
| EntityType | |
-------------------- |
-------------
|
V
--------------------
| EntityAttributes | ------------------ ---------------------------
-------------------- | Attributes | | StringAttributes |
| EntityId PK,FK | ------------------ ---------------------------
| AttributeId FK | -> | AttributeId PK | -> | StringAttributeId PK,FK |
| AttributeValue | | AttributeType | | AttributeName |
-------------------- ------------------ ---------------------------
AttributeValue列被实现为一个sql_变量列,我为它实现了一个NHibernate.UserTypes.IUserType
我可以创建一个EntityAttribute实体并直接将其持久化,这样层次结构的一部分就可以工作了
我只是不知道如何将EntityAttributes集合映射到实体
注意:对于给定的EntityId/AttributeId组合,EntityAttributes表可能(并且确实)包含多行:
EntityId AttributeId AttributeValue
-------- ----------- --------------
1 1 Blue
1 1 Green
StringAttributes行在本例中如下所示:
StringAttributeId AttributeName
----------------- --------------
1 FavoriteColor
如何有效地将此数据模型映射到我的实体域,以便Entity.Attributes(“FavoriteColors”)返回最喜爱的颜色集合?键入为System.String?开始
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>();
});
}
}
类实体
{
公共虚拟整数Id{get;set;}
内部受保护的虚拟ICollection属性内部{get;set;}
公共IEnumerable属性(字符串attributeName)
{
返回属性内部
.Where(x=>x.Attribute.Name==attributeName)
.选择(x=>x.Value)
.Cast();
}
}
类EntityAttribute
{
公共虚拟属性{get;set;}
公共虚拟对象值{get;set;}
}
类EntityMap:ClassMap
{
公共实体映射()
{
HasMany(e=>e.AttributesInternal)
.Table(“EntityAttributes”)
.KeyColumn(“EntityId”)
//EntityAttribute不能是实体,因为没有真正的主键
//(EntityId,[AttributeId]不是唯一的)
.组件(c=>
{
c、 引用(ea=>ea.Attribute,“AttributeId”).Not.LazyLoad();
c、 Map(ea=>ea.Value,“AttributeValue”).CustomType();
});
}
}
如果您计划按属性值查找实体,我不确定sql\u变体是否工作正常。你应该试试这个。