Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a List<string> to a delimited string with Fluent NHibernate

My model looks something like this:

public class Product
{
    public string Name {get; set;}
    public string Description {get; set;}
    public double Price {get; set;}
    public List<string> Features {get; set;}
}

I want my database table to be flat - the List should be stored as a delimited string: Feature one|Feature two|Feature three for example.

When retrieved from the db, it should place each of those items back into a List

Is this possible?

like image 832
Alex Avatar asked Feb 04 '23 00:02

Alex


1 Answers

I'm doing the very same in my current project, only I'm persisting a collection of enums as pipe-delimited numbers. It works the same way.

public class Product
{
    protected string _features; //this is where we'll store the pipe-delimited string
    public List<string> Features {
        get
        {
            if(string.IsNullOrEmpty(_features)
                return new List<String>();
            return _features.Split(new[]{"|"}, StringSplitOptions.None).ToList();
        }
        set
        {
            _features = string.Join("|",value);
        }
    }
}

public class ProductMapping : ClassMap<Product>
{
    protected ProductMapping()
    {
        Map(x => x.Features).CustomType(typeof(string)).Access.CamelCaseField(Prefix.Underscore);
    }
}
like image 133
DanB Avatar answered Feb 05 '23 16:02

DanB