且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

流利的nhibernate组件一对多

更新时间:2022-10-29 23:14:32

如果您有直接的一对多关联到一个组件的集合(即没有 ComponentClass 包装器),那么你可以直接映射它:

  HasMany(x => x.Elements)
.AsSet()
.Table(ElementTable)
.KeyColumn(KeyColumn )
.Cascade.All()
.Component(x =>
{
x.Map(c => c.Id);
x。 Map(c => c.Time);
})
.LazyLoad();


I have couple of classes and want to map them correctly to database:

public class A
{
    public virtual Guid Id { get; private set; }
    public virtual ComponentClass Component { get; set; }
}

public class ComponentClass 
{
    public virtual IList<B> Elements { get;set; }
}

public class B
{
    public virtual Guid Id { get; private set; }
    public virtual DateTime Time { get; set; }
}

I map them using fluent mappings like that:

public class AMap : ClassMap<A> 
{
    public A() {
        Id(x => x.Id);
        Component(x => x.Component,
                  c => c.HasMany(x => x.Elements).Inverse().Cascade.All());
    }
}

public class BMap : ClassMap<B>
{
    public B() {
        Id(x => x.Id);
        Map(x => x.Time);
    }
}

When I save my entity, I have class A mapped to one table and class B to another as expected. But I have nulls in Component_id column. Can you tell me what am I missing here?

If you have a one-to-many association direct to a collection of components (ie. without the ComponentClass wrapper as per the question) then you can map it directly:

HasMany(x => x.Elements)
    .AsSet()
    .Table("ElementTable")
    .KeyColumn("KeyColumn")
    .Cascade.All()
    .Component(x =>
    {
        x.Map(c => c.Id);
        x.Map(c => c.Time);
    })
    .LazyLoad();