Search code examples
nhibernatefluent-nhibernate-mapping

NHibernate - Has Many - Has One - ICriteria


I have the following tables:

Table Material
Id
Table Zone
Id
Table MaterialZone
Id
Material_Id
Zone_Id
Price


Edit
What I need is to have the MaterialZone (whit the current Zone) in the Material object, I dont know if I can solve it by mapping or by Query, because the relational "Id" its in the MaterialZone table.

The Maps

MapMaterialZone()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        ///Properties
        References(x => x.Material).Column("material_id");
        References(x => x.Zone).Column("zone_id");
    }

MapZona()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        ///Properties
    }
MapMaterial()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        ///Properties
        //HasMany(x => x.ListMaterialZone);
        //HasOne(x => x.IndividualMaterialZone).PropertyRef(MaterialZona => MaterialZona.Material);
    }

I first tried to add and map The IList<"MaterialZone">, and the MaterialZone property searches in the list and returns the one with the current Zone, but the Query and the controls got too slow. (Im working with Access an ComponentOne)

I have tried to solve this from mapping and Querys but I havent had much luck. I have medium experience in NHibernate and Mapping and little experience in QueryOver and ICriteria

Im open to all solutions (but unfortunatelly Access has to stay) Thanks.


Solution

  • I´ve found a solution, my mapping

    MaterialMap
    HasOne(x => x.MaterialZona).PropertyRef(materialZona => materialZona.Material);
    

    and the final QueryOver

    ISession session = GetSession();
    Zona zonaPredeterminada = GetDefaultZone();
    Material materialAlias = null;
    MaterialZona materialZonaAlias = null;
    
    return session.QueryOver<Material>(() => materialAlias)
        .JoinQueryOver(mat => mat.MaterialZona, () => materialZonaAlias)
        .Where(mZ => mZ.Zona.Id == zonaPredeterminada.Id)
        .And(mZ => mZ.Material.Id == materialAlias.Id)
        .List();