I have a custom DateTime-Range class which is used in several models:
public class Entity
{
public DateTimeRange Usage {get; set; }
}
public class DateTimeRange
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
How can I achieve that the properties are store in the same database table as the parent entity (TPH)?
For the code below I want this datatable:
Id | Name | Validity_From | Validity_To | Usage_From | Usage_To
1 | Hummer | 2015-01-01 | 2999-12-31 | 2021-09-01 | 2021-09-15
I couldn't find a solution for this specific case in the EF Core documentation (TPH/TPT).
I found a solution in the Microsoft docs:
Owned Entity Types - EF Core | Microsoft Docs[
^]
In this approach I had to do the mapping myself. I'm looking for a general mapping. If this owned entity is used in 30 models, I don't want to mapp this in all models.
Note:
Using DateTimeOffset is not an option.
The class property could also be something else like a phone object (phone.pre, phone.number).
What I have tried:
using System;
namespace Foo
{
public class Testdata
{
public void Test()
{
dynamic dbContext = new Object();
var car = new Car()
{
Name = "Hummer",
Validity = new() { From = new(2015, 1, 1), To = new(2999, 12, 31) },
Usage = new() { From = new(2021, 9, 1), To = new(2021, 9, 15) }
};
dbContext.Cars.Add(car);
dbContext.SaveChanges();
}
}
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeRange Validity { get; set; }
public DateTimeRange Usage { get; set; }
}
public class DateTimeRange
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
}