0

In my domain model I have a property type Property<T> which holds a Value and a DefaultValue just beside:

public class Property<T> : Entity
{
    public Property(T defaultValue)
    {
        DefaultValue = defaultValue;
        Value = defaultValue;
    }

    public T DefaultValue { get; }

    public T Value { get; set; }
}

I like to use the default initialization to have the default value set when using that property type:

public class Device : Entity<Guid>
{
    public Property<double> Calibration { get; } = new Property<double>(5.0);
}

I want to save Value for the Calibration property in the database using EF Core and I also want keep the DefaultValue as it comes from the default initialization.

Question: do I need to save also DefaultValue in the database or can I tell EF Core somehow to use it from the default constructed object when doing the Get() call on the repository for entity type Device?

This would save me the "effort" to store the complete Property as an entity in the database when only Value needs to be stored (and the DefaultValue comes by the type definition). Using a ValueConverter to save only the Value of the Calibration property would be fine for that.

Before I had the domain objects mapped to entities but now I try to merge them to get rid of the automapping step in between.

Phija
  • 41
  • 3
  • You can define a converter for each property when you can precise the default value. See the documentation for more detail : [Value Conversions](https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions). – vernou Jun 29 '21 at 15:47
  • It's usually not a good idea to [initialize reference navigation properties](https://stackoverflow.com/a/20773057/861716). You better use a factory for `Entity` objects. – Gert Arnold Jun 29 '21 at 20:40
  • 1
    Thanks to @vernou I was reading even more on ValueConverter's documentation and found the part about [Composite objects](https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations#composite-value-objects). So the way to go could be: saving default value as well together with the value by simply json-serializing it using a ValueConverter. At least unless EF Core 6.0 is ready with the [feature of splitting an object to multiple columns](https://github.com/dotnet/efcore/issues/13947). – Phija Jun 30 '21 at 05:47

0 Answers0