Reputation: 5501
I have a single property that I want stored in two separate mysql columns.
The property is defined as:
public virtual List<Point> Vertices { get; set; }
Point is System.Drawing.Point.
My database table has two columns that i want this one property saved into:
xarr VARCHAR(3000)
yarr VARCHAR(3000)
If Vertices contained the following points:
{1,2}
{3,4}
{5,6}
When the entity was saved by Nhibernate, i would like the
yarr column to be populated with "2,4,6"
xarr column to be populated with "1,3,5"
Please do not advise me on redesigning the database schema. To answer my question I would like to know the best way to achieve this in NHibernate, given the constraints above.
Upvotes: 1
Views: 491
Reputation: 706
I will admit to not having used NHibernate, but can you just add two properties to the model class for the xarray and yarray strings
public string XArray { get { return string.Join(",", this.Vertices.Select(v => v.X.ToString())); } }
public string YArray { get { return string.Join(",", this.Vertices.Select(v => v.Y.ToString())); } }
and then persist those?
edit: Alright, if I'm reading this correctly, it sounds like you want to create a VerticesType
public class VerticesType : IUserType
{
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var retval = new List<Point>();
var xCoords = ((string) NHibernateUtil.String.NullSafeGet(rs, names[0])).Split(",");
var yCoords = ((string) NHibernateUtil.String.NullSafeGet(rs, names[1])).Split(",");
for(i = 0; i < xCoords.Length; i++)
{
retval.Add(new Point(int.Parse(xCoords[i]), int.Parse(yCoords[i])));
}
return retval;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var list = value as List<Point>;
if( list == null )
{
NHibernateUtil>String.NullSafeSet(cmd, null, index);
NHibernateUtil>String.NullSafeSet(cmd, null, index + 1);
return;
}
NHibernateUtil.String.NullSafeSet(cmd, string.Join(",", list.Select(v => v.X.ToString()), index);
NHibernateUtil.String.NullSafeSet(cmd, string.Join(",", list.Select(v => v.Y.ToString()), index + 1);
}
# rest of IUserType implementation here
}
Obviously with more error checking. Hope that helps.
Upvotes: 2