dev*_*rus 15 nhibernate nhibernate-mapping entity-attribute-value
我正在尝试利用NH来映射到数据模型,这是对EAV/CR数据模型的宽松解释.
我有大部分工作,但我正在努力映射Entity.Attributes集合.
以下是有问题的表格:
--------------------
| Entities |
--------------------
| EntityId PK |-|
| EntityType | |
-------------------- |
-------------
|
V
--------------------
| EntityAttributes | ------------------ ---------------------------
-------------------- | Attributes | | StringAttributes |
| EntityId PK,FK | ------------------ ---------------------------
| AttributeId FK | -> | AttributeId PK | -> | StringAttributeId PK,FK |
| AttributeValue | | AttributeType | | AttributeName |
-------------------- ------------------ ---------------------------
Run Code Online (Sandbox Code Playgroud)
AttributeValue列实现为sql_variant列,我为它实现了NHibernate.UserTypes.IUserType.
我可以创建一个EntityAttribute实体并直接保存它,以便部分层次结构正常工作.
我只是不确定如何将EntityAttributes集合映射到Entity实体.
请注意,EntityAttributes表可以(并且确实)包含给定EntityId/AttributeId组合的多个行:
EntityId AttributeId AttributeValue
-------- ----------- --------------
1 1 Blue
1 1 Green
Run Code Online (Sandbox Code Playgroud)
对于此示例,StringAttributes行如下所示:
StringAttributeId AttributeName
----------------- --------------
1 FavoriteColor
Run Code Online (Sandbox Code Playgroud)
如何有效地将此数据模型映射到我的Entity域,以便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>();
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1496 次 |
| 最近记录: |