Can EF Core map a GET (calculated) property?

.net .net-core entity-framework-core sql-server

Question

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.

1
1
2/21/2020 8:28:16 PM

Accepted Answer

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; }
1
2/21/2020 8:58:04 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow