✅ EntityFrameworkCore lists
This has probably been asked before, but is it possible to store a
List<T>
in a npsql database using EntityFrameworkCore?
If so, how would I go about it?
(For context, I have a DbSet<Guild>
, and I want the model to store data on guilds, and one of the things I want to store is a collection of tags)3 Replies
Yes, regardless of your database type. This is known as a many-to-one relationship. However, your list items can't be a primitive; they must be a separate entity that lives in the database.
For example, you can create a Tag entity which contains the tag's name. In the Tag entity, you may optionally include a reference to the associated Guild and/or its ID.
Here's an example model:
Guild:
- string Id
- List<Tag> Tags
Tag:
- string Id
- string Name
- Guild Guild (optional)
- string GuildId (optional)
However, this won't work as string is a primitive type:
Guild:
- string Id
- List<string> Tags
That said, it is possible to store direct string lists, but it's not as straightforward. You will have to write a value converter to convert string lists to a type that is supported by EF core and back (like a delimited or JSON string which is not a good idea at all and violates the atomicity principle in ACID).
https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions
Value Conversions - EF Core
Configuring value converters in an Entity Framework Core model
Thanks!
No problem 🙂