Search code examples
c#fluent-nhibernatenhibernate-mapping

How to use/map a database view to populate a contained collection?


I have these classes:

public class FloorFill
{
    protected FloorFill(){}
    public virtual ProductCatalog Catalog { get; set; }
    public virtual Inventory BatchedItem { get; set; }
    public virtual Transaction Batch { get; set; }
    public virtual int ItemReference { get; set; }
    public virtual IList<InventoryLocation> BackstockLocations { get; set; }
}
public class InventoryLocation
{
    public InventoryLocation(){}
    public virtual int Id { get; set; }
    public virtual int ItemReference { get; private set; }
    public virtual Location Where { get; set; }
    public virtual int HowMany { get; set; }
}

I have a database view that aggregates Items by location and some other filtering. I would like to reference this view in the mapping to populate the FloorFill.BackstockLocations collection.

What approach should I be using to get this collection populated? I would like for the collection to lazy load, but at this point, I'd just be happy to get data.

Here are the mapping files:

public class FloorFillMap : EntityBaseMap<FloorFill>
{        
    public FloorFillMap()
    {
        Map(x => x.ItemReference);
        References(x => x.Catalog, "ProductCatalogId")
                        .WithForeignKey();
        References(x => x.Batch, "TransactionId")
                .WithForeignKey()
                .Cascade.SaveUpdate();
        References(x => x.BatchedItem, "InventoryId")
                .WithForeignKey()
                .Cascade.SaveUpdate();
        HasMany(x => x.BackstockLocations)
            .KeyColumnNames.Add("ItemReference")
            .Inverse()
            .Cascade.None()
            .LazyLoad();
    }
}

public class InventoryLocationMap : ClassMap<InventoryLocation>
{
    public InventoryLocationMap ()
    {
        WithTable("InventoryLocations");
        Id(x => x.Id);
        References(x => x.Where, "LocationId")
            .FetchType.Join()
            .Cascade.None();
        Map(x => x.HowMany);
        ReadOnly();
    }
}

The resulting query is:

SELECT 
    this_.Id as Id33_0_, 
    this_.Created as Created33_0_, 
    this_.ItemReference as ItemRefe3_33_0_, 
    this_.Modified as Modified33_0_, 
    this_.RowVersion as RowVersion33_0_, 
    this_.ProductCatalogId as ProductC6_33_0_, 
    this_.TransactionId as Transact7_33_0_, 
    this_.InventoryId as Inventor8_33_0_ 
FROM [FloorFill] this_

Solution

  • Mapping a view is the same as mapping a table, as long as you don't try to update it.

    What are you trying to do in this statement?

    References(x => x.Where, "LocationId")
      .FetchType.Join().WithColumns("Id").Cascade.None();
    

    The "LocationId" is the key column name, but the WithColumns call will overwrite that value.

    An error or some other indication of what's happening or not happening would help.