Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ef code first seed many to many relationship

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?

like image 991
eiu165 Avatar asked Feb 14 '26 13:02

eiu165


1 Answers

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)

like image 108
Mark Oreta Avatar answered Feb 17 '26 10:02

Mark Oreta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!