NHibernate:如何根据鉴别器类型过滤映射集合

时间:2011-11-17 08:22:59

标签: nhibernate fluent-nhibernate nhibernate-mapping

的信息: 有一个组对象。可以邀请用户加入群组。有两种类型的组邀请:外部和内部。所有邀请都使用鉴别器存储在单个表中。组对象仅了解内部邀请。

问题在Invite表中有两条记录。一个用于内部,一个用于外部。如果我加载该组,我将看到两个邀请甚至集合都是InternalInvite类型。 InternalInvite result

SELECT internalin0_.Group_id as Group3_1_,
   internalin0_.Id       as Id1_,
   internalin0_.Id       as Id0_0_,
   internalin0_.Group_id as Group3_0_0_,
   internalin0_.User_id  as User5_0_0_

FROM [AbstractInvite] internalin0_ 内部inin0_.Group_id ='be60b160-659e-4157-b033-9f9e00e346c7'

当我将ISet集合类型更改为AbstractInvite时,它将加载具有正确类型的所有邀请。

问题如何将集合属性仅映射到InternalInvites?

我会尽量尽量减少代码。

群组映射:

public class Group
{
    public Group()
    {
        InternalInvitations = new HashedSet<InternalInvite>();
    }
    public virtual Guid Id { get; set; }
    public virtual ISet<InternalInvite> InternalInvitations { get; set; }
}

public class GroupMap : ClassMap<Group>
{
    public GroupMap()
    {
        Id(x => x.Id);
        HasMany(x => x.InternalInvitations).Inverse();
    }
}

外部和内部邀请+映射:

public abstract class AbstractInvite
{
    public virtual Guid Id { get; set; }
    public virtual Group Group { get; set; }
}

public class ExternalInvite : AbstractInvite
{
    public virtual string Name { get; set; }     
}

public class InternalInvite : AbstractInvite
{
    public virtual User User { get; set; }
}

public class AbstractInviteMap : ClassMap<AbstractInvite>
{
    public AbstractInviteMap()
    {
        Id(x => x.Id);
        References(x => x.Group);
        DiscriminateSubClassesOnColumn("type");
    }
}

public class ExternalInviteMap : SubclassMap<ExternalInvite>
{
    public ExternalInviteMap()
    {
        Map(x => x.Name);
    }
}

public class InternalInviteMap : SubclassMap<InternalInvite>
{
    public InternalInviteMap()
    {
        References(x => x.User);
    }
}

2 个答案:

答案 0 :(得分:2)

我会回答自己。

我能够通过以下代码实现我的目标:

public class AbstractInviteMap : ClassMap<AbstractInvite>
{
    public AbstractInviteMap()
    {
        Id(x => x.Id);
        References(x => x.Group);
        DiscriminateSubClassesOnColumn("type").AlwaysSelectWithValue();
    }
}

参考:Discriminator in NHibernate documentation. Focus on 'force' option.

答案 1 :(得分:1)

quickfix / workaround将是

HasMany(x => x.InternalInvitations).Inverse().Where("type = 'Namespace.InternalInviteMap'");