【问题标题】:(EF) Mapping Multiple Columns of Same Type To Array/List Property In POCO Class(EF) 将相同类型的多个列映射到 POCO 类中的数组/列表属性
【发布时间】:2021-07-02 03:18:01
【问题描述】:

我有一个包含多个列(名为 Day0Day1 等)的表,每个列都存储一个 INT,并且想知道是否可以在 POCO 类中声明 public Days int[] {get; set;} 并使用 Fluent API将每个 Day<n> 列映射到数组中的一个项目,而不是为每一列声明一个单独的属性。

【问题讨论】:

    标签: entity-framework-core poco


    【解决方案1】:

    您可以将Indexer property 与拥有的实体结合使用。

    你的实体

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

    拥有天数

    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");
        });
    

    应用程序代码

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

    【讨论】:

    • 这看起来很有希望,但我不确定这正是我的想法。我不想在实体类本身上使用索引器,而是在像entity.Days[0] 这样的命名属性上使用。这是我能得到的最接近的吗?
    • 我已经检查了 Indexer+Owned 实体,插入工作正常
    • 所以将索引器放在Days 拥有的YourEntity 实体上?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2011-10-27
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多