(EF) Mapping Multiple Columns of Same Type To Array/List Property In POCO Class

I have a table with multiple columns (named Day0, Day1 etc) each storing an INT and would like to know if it is possible to declare public Days int[] {get; set;} in the POCO class and use Fluent API to map each Day<n> column to an item in the array rather than declare a separate property for each column.

Upvotes: 0

Views: 1178

Answers (1)

FireAlkazar
FireAlkazar

Reputation: 1882

You can use Indexer property in combination with the owned entity.

YourEntity

public OwnedDays? Days { get; set; } = new();

OwnedDays

public class OwnedDays
{
    private readonly Dictionary<string, int?> _data = new Dictionary<string, int?>
    {
        { "0", default },
        { "1", default },
        { "2", default },
        { "3", default },
    };

    public int? this[string key]
    {
        get => _data[key];
        set => _data[key] = value;
    }
}

Context.OnModelCreating

modelBuilder.Entity<YourEntity>().OwnsOne(
    ye => ye.Days,
    d => {
        d.IndexerProperty<int?>("0").HasColumnName("Day0");
        d.IndexerProperty<int?>("1").HasColumnName("Day1");
        d.IndexerProperty<int?>("2").HasColumnName("Day2");
        d.IndexerProperty<int?>("3").HasColumnName("Day3");
    });

Application code

var entity = new YourEntity();
entity.Days["0"] = 0;
entity.Days["1"] = 1;

Upvotes: 1

Related Questions