Eitan
Eitan

Reputation: 1504

Update foreign keys in an n:n relationship - Entity Framework Code First Migrations

I'm using Entity Framework code first migrations. There is an n:n relationship between Profile and Languages (A Profile can have many Languages). I was wondering how I can update the list of languages for the profile if I have the language IDs (foreign key). For a 1:1 relationship (i.e. if Profile could only have 1 Language), I could just update LanguageID but for n:n I don't have a list of LanguageIDs to update so it means I have to make an extra trip to the database to retrieve the languages and initialize the Language property of the profile object. Is there any way to get around that?

Upvotes: 0

Views: 99

Answers (1)

Steve Greene
Steve Greene

Reputation: 12324

Since you titled this migrations I'll assume you want to do some sort of Seeding? I'll start with this answer so we have some code to discuss:

protected override void Seed(ApplicationContext context)
{
    var languageIds = new List<int> {1,2,3,4};  // FK to language. Are you assigning same list to all profiles?

    var profiles = context.Profiles.Include(p => p.Languages).ToList();
    foreach (var profile in profiles)
    {
        // Since you mention updating, you may need to remove old languages
        if (profiles.Languages.Any())
        { delete children... }

        // add new languages. You could add a test so you only seed when no languages are present
        foreach (var languageId in LanguageIds)
        {
            profile.Add(new Language {LanguageId = languageId};
        }
    }

    context.SaveChanges();
}

Upvotes: 1

Related Questions