Is there a way to use ARRAYs in Entity Framework +

2020-02-09 13:29发布

问题:

Is it possible to use arrays in Entity Framework with PostgreSql?

Suppose, for instance, we had the POCO class

        public class MyTable
        {
            [Key]
            [Column("gid")]
            public int Gid { get; set; }
            [Column("name")]
            public string Name { get; set; }
            [Column("email")]
            public string Email { get; set; }
            [Column("somedata")]
            public int[] SomeData { get; set; }
        }

At this point Entity Framework simply does not create the column "somedata" and skips it. Is there a way to do this anyway? And by that I mean not having to use a separate table. Postgres arrays come in handy at times where you want to store a small or limited number of values into a single column.

回答1:

It's possible to do this if you use Entity Framework Core with the Npgsql EF Core provider.

The code-first approach would be:

[Column("somedata", TypeName = "integer[]")]
public int[] SomeData { get; set; }