Reputation: 6261
I have a many to many relationship.
a tag can have multiple articles and an article can have multiply tags.
public class Article : Entity
{
[StringLength(150)]
public string Name { get; set; }
public string Content { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag : Entity
{
public string Name { get; set; }
public ICollection<Article> Articles { get; set; }
}
the ef codefirst creates a table called TagArticles
with columns Tag_Id
and Article_Id
I tried to seed like this
protected override void Seed(Context context)
{
var articles = new List<Article>();
for (int i = 0; i < 10; i++)
{
articles.Add(new Article { Name = "test " + i, Content = "lourm ipsum" });
}
var tags = new List<Tag>();
for (int i = 0; i < 10; i++)
{
tags.Add(new Tag { Name = "tag " + i , Articles = new Article[]{ articles[0] }});
}
context.Articles.AddOrUpdate(x => x.Name, articles.ToArray());
context.Tags.AddOrUpdate(x => x.Name, tags.ToArray());
}
but the TagArticles table is empty after the migration, how do I seed the bridge table?
Upvotes: 3
Views: 1660
Reputation: 10416
The code you had above worked for me when I put it in, but I had to add the Primary Keys in order for the database to actually save.
Where are you setting the primary keys? Is that in the Entity inheritance?
After you seed, are there Articles and Tags in the database (there wasn't for me until I corrected the PK issue)
Upvotes: 1