How do I map a collection of strings to the database using EF6 Code First.
Here is my scenario. I have a book class with a collection of strings
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string ISBN { get; set; }
public virtual ICollection<string> Tags { get; set; }
}
I want to map this collection to the following tables. I don’t want the strings serialised into a single field because I want to query them in the database.
CREATE TABLE [dbo].[Books](
[Id] [int] NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[ISBN] [nchar](17) NOT NULL,
CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
CREATE TABLE [dbo].[BookTags](
[BookId] [int] NOT NULL,
[Tag] [nvarchar](50) NOT NULL,
CONSTRAINT [FK_BookTags_Book] FOREIGN KEY ([BookId]) REFERENCES [Books]([Id]),
CONSTRAINT [FK_BookTags_Tag] UNIQUE ([Tag]),
CONSTRAINT [PK_BookTags] PRIMARY KEY ([BookId], [Tag])
)
GO
I’ve read somewhere that primitive collections are not supported in EF but this looks like a simple scenario and we’re on version 6 now. So is this possible and if so how can I do this using EF6 code first?