0

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?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
Joe K
  • 1
  • 2
  • 1
    Nothing has changed in that regard. You need to create and map properly a `BookTag` entity class. – Ivan Stoev Oct 16 '17 at 17:21
  • @IvanStoev Thanks, it's a shame it's not supported because it introduces needless foreign keys and coding overhead. – Joe K Oct 17 '17 at 08:01
  • 1
    @Pawel I'll mark this a duplicate as there's been no change in Entity Framework. Thanks – Joe K Oct 17 '17 at 08:02

0 Answers0