I have a model class that has an array of objects which I want to store in the database. In order to fit this data into a single row and column; I have a get
property which concatenates the array and returns a single string. I want to store this concatenated string in the database.
[NotMapped]
public object[] Values { get; set; }
public string Value
{
get
{
return string.Join("|", this.Values);
}
}
I have confirmed that the Value property contains the string that I expect. However, this does not save to the database; it just saves it as NULL. I do not have any special mapping code in place; it is relying on the defaults of having the column name match the property name.
The closest thing I have found it this tutorial which describes using the HasField() method to map the column to a private field instead of a property; but in my case it's not just that I have a private set; it's that I don't have any set property at all.
Why don't you just do somethig like this?
private object[] values;
[NotMapped]
public object[] Values {
get => values;
set {
if (value != values);
values = value;
Value = string.Join("|", value);
}
}
public string Value { get; set; }
Another approach not to mix business and persistence structures.
Other parts of application should care/know how data is stored.
public class BusinessObject
{
public object[] Values { get; set; }
}
public class ValuesEntity
{
public static ValuesEntity From(BusinessObject object)
{
return new ValuesEntity { Values = string.Join("|", object.Values) };
}
public string Values { set; set; }
public BusinessObject ToBusinessObject()
{
return new BusinessObject { Values = Values.Split("|") };
}
}
With this approach you will explicitly "tell" other developers or reader of the code your intentions.
Working with different classes for each responsibility(business logic or persistence) will be simpler because both responsibilities are isolated from each other.