How to save a primitive array using nHibernate

Given this object:

public class Product { public double[] Prices; } 

With this table structure:

 Product (Id) Price (ProductId, Order, Price) 

I am confused about the difference between when to use a list, bag, primitive array, array, etc. I could not find many explanations in a primitive array.

An important requirement is that array elements must always be stored and retrieved in the same order and contain duplicate values.

My question is: what will the comparison between the two tables look like?

+4
source share
2 answers

To maintain order, you need <list />, and provide an index column to keep track of the order of the element (or entity). You may have a list of elements (simple types) that seems to be better for you.

+3
source

If you know for sure that your data will never have inconsistent array data as prices (the index always starts at 0 for all products, in no case does it index holes or duplicates for the product), match it as <array> .

(And it's better to switch prices to decimal instead of double .)

 <class name="Product"> <id name="Id" generator="..." /> <array name="Prices" table="Price"> <key column="ProductId" /> <index column="Order"/> <element type="decimal" length="19" precision="4"> <column name="Price" /> </element> </array> </class> 

You can also use a list as written in the Felice answer , but then enter your property as IList<decimal> .

As with primitive-array , it seems that we just donโ€™t need to worry about it, this is a mapping inherited from java Hibernate and corresponding to a concept that is primitive, not related to C #.
This was probably the meaning of Paco's comment , which I did not understand at first. This is confirmed by this NH issue .

If you cannot guarantee the consistency of indexes in the database (not always starting at 0, they may have holes or duplicate indexes for the same product ...), then you will have to change your model to match your prices as <set> child objects ( ISet<Price> Prices ) with an index that you will process with your own code. (The custom part when loading data can be processed using the order-by="Order" attribute on your set display).
Duplicate prices for the product will also be different rows in the database to process the index, which will be different. Thus, my recommendation is to use set rather than bag , since duplicate prices will be really different objects.

0
source

Source: https://habr.com/ru/post/1336490/


All Articles