NHibernate: how to enable lazy loading on one-to-one mapping

后端 未结 5 1829
萌比男神i
萌比男神i 2020-12-03 11:22

One-to-one relations within nhibernate can be lazyloaded either \"false\" or \"proxy\". I was wondering if anyone knows a way to do a lazy one-to-one mapping.

I work

5条回答
  •  既然无缘
    2020-12-03 11:41

    After reading the answers here, I´ve manage to get it to work. I´m just going to add this example because I´m using a One to One relation with Constrained= False and because it´s a Mapping by Code Example

    Two Classes:

    public class Pedido:BaseModel
    {
        public virtual BuscaBase Busca { get; set; }
    }
    
    public class BuscaBase : BaseModel
        {       
            public virtual Pedido Pedido { get; set; }
        }
    

    Mappings:

    public class PedidoMap : ClassMapping
    {
        public PedidoMap()
        {
             Id(x => x.Id, x => x.Generator(Generators.Identity));            
    
             ManyToOne(x => x.Busca, m => 
             { 
                 m.Cascade(Cascade.DeleteOrphans);
                 m.NotNullable(true); m.Unique(true);
                 m.Class(typeof(BuscaBase));
             });    
        }
    }
    
    public class BuscaBaseMap : ClassMapping
    {
        public BuscaBaseMap()
        {            
            Id(x => x.Id, x => x.Generator(Generators.Sequence, g => g.Params(new { sequence = "buscaefetuada_id_seq" })));
    
            OneToOne(x => x.Pedido, m =>
            {
                m.Lazy(LazyRelation.NoProxy);
                m.Constrained(false);
                m.Cascade(Cascade.None);
                m.Class(typeof(Pedido));
            });            
        }
    }
    

    Note: I was Using for the one-to-one mapping m.PropertyReference(typeof(Pedido).GetProperty("Busca")); but this does't work for the lazy loading. You have to specify the relation using the Class

    A quick brief about the Constrained = False used in here, the "Pedido" object might not exist in "BuscaBase" object.

提交回复
热议问题