MVC creating a list as a model property not being added as foreign key to DB with code first entity framework

456 views Asked by At

I am starting a code first EF MVC project. Below is the code for a Message model that I am creating. Is it possible to create a tags property that is a list of tags (another model I created) like I am attempting below?

public class Message
{
    public int Id { get; set; }
    public string Text { get; set; }
    public byte[] Attachment { get; set; }
    [Required]
    public MessageBoard MessageBoard { get; set; }

    [Required]
    public virtual List<Tag> Tags { get; set; } 

}

After attempting the update-database -verbose command, I see that it does not add a Tags class to my database. The console shows this db command for messages:

CREATE TABLE [dbo].[Messages] (
    [Id] [int] NOT NULL IDENTITY,
    [Text] [nvarchar](max),
    [Attachment] [varbinary](max),
    [MessageBoard_Id] [int] NOT NULL,
    CONSTRAINT [PK_dbo.Messages] PRIMARY KEY ([Id])
)

How can I create this foreign key relationship between messages and tags?

1

There are 1 answers

1
Marc Cals On BEST ANSWER

I assume that you one Many to Many relationship to reuse existing tags.

First of all you have to add to your Tag class a reference to Message

public virtual List<Message> Messages { get; set; };

Then in your model configuration class you have to set the relation many to many, with the following code :

 modelBuilder.Entity<Message>()
                   .HasMany<Tag>(m => m.Tags)
                   .WithMany(t => t.Messages)
                   .Map(mt =>
                            {
                                mt.MapLeftKey("MessageID");
                                mt.MapRightKey("TagId");
                                mt.ToTable("MessagesTag");  //Name of table many to many
                            });

And don't forget to add class Tag in your DBContext too.

public DbSet<Tag> Tag { get; set; }