FluentNhibernate IDictionary <Entity, ValueObject>
I had a mapping for the IDictionary<StocksLocation,decimal> property, this was a mapping:
HasMany<StocksLocation>(mq => mq.StocksLocation) .KeyColumn("IDProduct") .AsEntityMap("IDLocation") .Element("Quantity", qt => qt.Type<decimal>()); Now I have changed from decimal to a Value: Quantity object.
Quantity has two properties: decimal Value and Unit Unit (where Unit is an enumeration).
Now I need to display IDictionary<StocksLocation,Quantity> , how can I achieve this?
Thanks in advance
Option 1: map it as an object
I assume the table looks something like this:
CREATE TABLE Quantity ( ID int NOT NULL, IDProduct int NOT NULL, IDLocation int NOT NULL, Value decimal(18,2) NOT NULL, Unit int NOT NULL, PRIMARY KEY (ID), FOREIGN KEY (IDProduct) REFERENCES Product (ID), FOREIGN KEY (IDLocation) REFERENCES StocksLocation (ID), UNIQUE KEY (IDProduct, IDLocation) ); Go ahead and map Quantity as an entity class:
public class QuantityMap : ClassMap<Quantity> { public QuantityMap() { Id(x => x.Id); References(x => x.Product, "IDProduct"); References(x => x.Location, "IDLocation"); Map(x => x.Value); Map(x => x.Unit); } } ... and then change the display of Product.StocksLocation to:
HasMany<StocksLocation, Quantity>(mq => mq.StocksLocation) .KeyColumn("IDProduct") .AsMap(x => x.Location); Option 2. Match it as a component
Since you commented that it is better not to match Quantity as an entity, consider how we will match this as a component. The * .hbm.xml mapping for the Product.StocksLocation dictionary will look like this:
<map name="StocksLocation" table="Quantity"> <key column="IDProduct" /> <index-many-to-many column="IDLocation" class="YourNamespace.StocksLocation, YourAssembly" /> <composite-element class="YourNamespace.Quantity, YourAssembly"> <property name="Unit" type="YourNamespace.Unit, YourAssembly" /> <property name="Value" type="System.Decimal, mscorlib" /> </composite-element> </map> How to do this with FluentNHibernate? As far as I know, there is no way to do this in the chest, so you have several options:
- Gabriel Schenker has implemented the
HasManyComponentmethod. He has a link to the source code for his project, but I don't know if this source includes the changes he made to FluentNHibernate. - If the source for its changes is not available, feel free to implement your own changes in FluentNHibernate and send them back to the community via Github.
- If this sounds like too many problems, FluentNHibernate has the ultimate reserve when everything else fails. This allows you to mix and match different matching methods. Auto-map some of your classes, write
ClassMapclasses for others, and write a * .hbm.xml file for any classes that cannot be mapped to FluentNHibernate.