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?
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
Then in your model configuration class you have to set the relation many to many, with the following code :
And don't forget to add class Tag in your DBContext too.