Entity Framework - Code First - Can't Store List<String>
Entity Framework does not support collections of primitive types. You can either create an entity (which will be saved to a different table) or do some string processing to save your list as a string and populate the list after the entity is materialized.
EF Core 2.1+ :
Property:
public string[] Strings { get; set; }
OnModelCreating:
modelBuilder.Entity<YourEntity>()
.Property(e => e.Strings)
.HasConversion(
v => string.Join(',', v),
v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
Update (2021-02-14)
The PostgreSQL has an array data type and the Npgsql EF Core provider does support that. So it will map your C# arrays and lists to the PostgreSQL array data type automatically and no extra config is required. Also you can operate on the array and the operation will be translated to SQL.
More information on this page.
This answer is based on the ones provided by @Sasan and @CAD bloke.
If you wish to use this in .NET Standard 2 or don't want Newtonsoft, see Xaniff's answer below
Works only with EF Core 2.1+ (not .NET Standard compatible)(Newtonsoft JsonConvert
)
builder.Entity<YourEntity>().Property(p => p.Strings)
.HasConversion(
v => JsonConvert.SerializeObject(v),
v => JsonConvert.DeserializeObject<List<string>>(v));
Using the EF Core fluent configuration we serialize/deserialize the List
to/from JSON.
Why this code is the perfect mix of everything you could strive for:
- The problem with Sasn's original answer is that it will turn into a big mess if the strings in the list contains commas (or any character chosen as the delimiter) because it will turn a single entry into multiple entries but it is the easiest to read and most concise.
- The problem with CAD bloke's answer is that it is ugly and requires the model to be altered which is a bad design practice (see Marcell Toth's comment on Sasan's answer). But it is the only answer that is data-safe.