Mapping entity oneToMany with fluent nhibernate

后端 未结 2 962
孤城傲影
孤城傲影 2021-01-21 02:20

The problem appears to be simple however I\'m having so much trouble trying to map this entities. I just can\'t see what am I doing wrong. Can you guys help me?

I have th

2条回答
  •  情话喂你
    2021-01-21 02:38

    After all, with these SQL scripts (adjust for SQL Server in my case)

    CREATE TABLE CLIENTE
    (
      CORE_ID                      int           NOT NULL,
      CORE_NUMERO_MEDIDOR          VARCHAR(50)
    )
    
    CREATE TABLE MEDIDOR
    (
      NUMERO_MEDIDOR  VARCHAR(50),
      MARCA_MEDIDOR   VARCHAR(50)
    )
    

    With these entities (all properties are virtual)

    public class Cliente
    {    
        public virtual int ClienteId { get; set; }  
        public virtual IList ListaMedidores { get; set; }   
        public virtual string NumeroMedidor { get; set; }       
    }
    public class Medidor
    {
        public virtual string NumeroMedidor { get; set; }
        public virtual string MarcaMedidor { get; set; }
        public virtual Cliente Cliente { get; set; }
    }
    

    and with only this one mapping in place:

    public class ClienteMap: ClassMap
    {
        public ClienteMap()
        {
            Table("CLIENTE");
            Id(x => x.ClienteId, "CORE_ID");
            Map(x => x.NumeroMedidor).Column("CORE_NUMERO_MEDIDOR");
            HasMany(x => x.ListaMedidores)
                .KeyColumn("NUMERO_MEDIDOR")
                .Component(com =>
                {
                    com.ParentReference(y => y.Cliente);
                    com.Map(y => y.MarcaMedidor, "MARCA_MEDIDOR");
                })
                .PropertyRef("NumeroMedidor")
                .Table("MEDIDOR")
                // .Inverse() // NO INVERSE, won't work
                .Cascade.All();
        }
    }
    

    I can confirm, that this query will work:

    var list = session.Query().Fetch(x => x.ListaMedidores).ToList();
    var firt = list.First().ListaMedidores.First();
    var last = list.First().ListaMedidores.Last();
    Assert.IsTrue(firt.MarcaMedidor != last.MarcaMedidor);
    

    BTW, this will be (my preferred) generated xml mapping:

    
        
          
          
        
        
          
            
          
          
            
            
              
            
          
        
        
          
        
    
    

    For documentation see:

    7.2. Collections of dependent objects

提交回复
热议问题