流畅的NHibernate以智能方式映射IDictionary <string,class =“”> </string,>

时间:2010-12-30 16:15:20

标签: nhibernate fluent-nhibernate nhibernate-mapping

鉴于这些课程:

using System.Collections.Generic;

namespace FluentMappingsQuestion
{
    public class Entity
    {
        public virtual int Id { get; set; }
        public virtual IDictionary<string, Property> Properties { get; set; }
    }

    public class Property
    {
        public virtual Entity OwningEntity { get; set; }
        public virtual string Name { get; set; }
        public virtual int Value { get; set; }
        public virtual decimal OtherValue { get; set; }
    }
}

如何使用NHibernate(最好是流利的味道)映射它们,以便这样做:

[Test]
public void EntityPropertyMappingTest()
{
    using (var session = _factory.OpenSession())
    {
        var entity = new Entity();

        // (#1) I would *really* like to use this
        entity.Properties["foo"] = new Property { Value = 42, OtherValue = 42.0M };

        session.Save(entity);
        session.Flush();

        // (#2) I would like the entity below to "update itself"
        // on .Save or .Flush. I got it to work with .Load()
        Assert.AreEqual(42, entity.Properties["foo"].Value);
        Assert.AreEqual(42.0M, entity.Properties["foo"].OtherValue);
        Assert.AreEqual("foo", entity.Properties["foo"].Name);
        Assert.AreEqual(entity, entity.Properties["foo"].Owner);
    }
}

我几乎设法用这些映射来做到这一点:

// class EntityMap : ClassMap<Entity>
public EntityMap()
{
    Id(x => x.Id);
    HasMany(x => x.Properties)
    .Cascade.AllDeleteOrphan()
    .KeyColumn("EntityId")
    .AsMap(x => x.Name);
}

// class PropertyMap : ClassMap<Property>
public PropertyMap()
{
    Id(x => x.Id);
    References(x => x.OwningEntity).Column("EntityId");
    Map(x => x.Name).Length(32);
    Map(x => x.Value);
{

我遇到的问题:

  • 如果我Entity.Properties .Inverse(),则会开始打破
  • 如果我没有.Inverse(),那么NHibernate会:INSERT(Entity), INSERT(Property), UPDATE(Property)而不只是INSERT(Entity), INSERT(Property)
  • 如果我Property.Name .Not.Nullable(),则会开始打破
  • 如果我没有.Not.Nullable(),我的数据库架构中有一个漏洞

我应该如何更改映射?

1 个答案:

答案 0 :(得分:4)

我通过指定此映射解决了这个问题:

HasMany<Property>(Reveal.Member<Entity>("InternalProperties"))
  .AsMap(p => p.Name)
  .Cascade.AllDeleteOrphan()
  .Inverse();

并创建IDictionary<string, Property>类型的两个属性:PropertiesInternalProperties。第一个是第二个代理字典,用于设置OwningEntity条目的NameProperty属性。