简体   繁体   中英

Fluent NHibernate - Mapping a dictionary of component/value type objects as a HasMany

I have a class, Item that has many Rates . They are keyed by an enum, RateType .

public class Item
{
    int Id {get;set;}
    IDictionary<RateType, Rate> Rates {get;set;}
    // some other stuff
}

public class Rate
{
    RateType Type {get;set;}
    decimal Amount {get;set;}
    decimal Quantity {get;set;}
}

I am overriding my mapping thusly:

public void Override(FluentNHibernate.Automapping.AutoMapping<Item> mapping)
{
    mapping.HasMany(x => x.Rates)
        .AsMap(x => x.Type)
        .KeyColumns.Add("Item_Id")
        .Table("InvoiceItem_Rates")
        .Component(x => x.Map(r => r.Amount))
        .Component(x => x.Map(r => r.Quantity))
        .Cascade.AllDeleteOrphan()
        .Access.Property();
}

This has two problems with it.

1) When I fetch an item, the Type is placed as the key of the Dictionary without problems. However, it is not assigned to the Type property within the Rate .

2) I'm expecting three columns in the table InvoiceItem_Rates ( Item_Id , Type , Quantity , and Amount . However, Amount is suspiciously absent.

Why are these things happening? What am I doing wrong?

This isn't perfect in my opinion as the enum key value is actually being stored as an integer instead of a string, but probably isn't an issue. The key here is that you can't have multiple calls to Component as it's going to overwrite your previous Component call with whatever the last one is. The correct way to call Component() is as below:

        Id(x => x.Id);
        HasMany(x => x.Rates)
            .AsMap(x => x.Type)
            .KeyColumn("Item_Id")
            .Table("InvoiceItem_Rates")
            .Component(x =>
                           {
                               x.Map(r => r.Amount);
                               x.Map(r => r.Quantity);
                           })
            .Cascade.AllDeleteOrphan();            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM