1

Solution: Finally I figure out what I needed to do, that was, simply clear languages list first. Now I can save job offer languages:

public void SaveJobOffer(JobOffer jobOffer)
        {
            if (jobOffer.ID == 0)
            {
                context.JobOffers.Add(jobOffer);
            }
            else
            {
                JobOffer existingJob = context.JobOffers.Find(jobOffer.ID);
                existingJob.Client = jobOffer.Client;
                (...)
                existingJob.Languages.Clear();
                existingJob.Languages = jobOffer.Languages;
            }
            context.SaveChanges();
        }

I'm working on an ASP.NET MVC5 project using C# and Razor engine with Visual Studio.

I would like to know how can I save many-to-many relationships using Entity Framework. I have the following tables but only JobOffer and Languages appear in the Edmx file:

JobOffer:

- Id
- Client
- ...

Jobffer_Languages:

- JobOfferId
- LanguageId
- ...

Languages:

- Id
- Name
- ...

To save a jobOffer I'm doing:

public void SaveJobOffer(JobOffer jobOffer)
{
            if (jobOffer.ID == 0)
            {
                context.JobOffers.Add(jobOffer);
            }
            else
            {
                context.JobOffers.Attach(jobOffer);
                context.Entry(jobOffer).State = EntityState.Modified;
                context.SaveChanges();
            }
}

But the languages are not saved. What do I need to do?

Thanks in advance


[EDIT]

My JobOffer controller code:

JobOffer jobOffer = new JobOffer();
jobOffer.ID = id;
...
var list = new List<Language>();
for (int i = 0; i < languages.Length; i++)
{
   Language language = repository.GetLanguageById(languages[i]);
   list.Add(language);
}
jobOffer.Languages = list;

repository.SaveJobOffer(jobOffer);
Miss Filipa
  • 31
  • 1
  • 4

2 Answers2

1

Using Entity Framework's code-first approach, your entity models should look like this:

public class JobOffer {
     [Key]
     public int Id { get; set; }

     public string Client { get; set; }
     public virtual ICollection<Language> Languages { get; set; }
}

public class Language {
     [Key]
     public int Id { get; set; }

     public string Name { get; set; }
     public virtual ICollection<JobOffer> JobOffers { get; set; }
}

This would create the following tables:

JobOffer
    - Id
    - Client

JobOfferLanguage
    - JobOfferId
    - LanguageId

Language
    - Id
    - Name

When adding a language to your JobOffer instance, you would just:

if(jobOffer.Languages == null) jobOffer.Languages = new List<Language>();
jobOffer.Languages.Add(newLanguage);

If this entity is persisted in the context:

context.JobOffers.Add(jobOffer);

EntityFramework would handle the constraints and relationship tables. Therefore, adding the corresponding association in JobOfferLanguage table.

It would also throw an error if newLanguage is not a valid entity, that is, it is null or has an invalid Id.

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • What you described is what i have. All parameters, like the client name, are persisted. Only the languages list with the corresponding relations are not saved. – Miss Filipa Dec 18 '14 at 17:12
0

Probably you need to map the relationship:

    public class YourContext : DbContext
    {
        //...
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<JobOffer>().
                HasMany(c => c.Languages).
                WithMany(p => p.JobOffers).
                Map(
                    m =>
                    {
                        m.MapLeftKey("JobOfferId");
                        m.MapRightKey("LanguageId");
                        m.ToTable("JobOfferLanguages");
                    });

        }
        //...
    }

You can check an example here:Creating a Many To Many Mapping Using Code First

If you want to know more how to map your your relationships, check this other link:Configuring Relationships with the Fluent API

ocuenca
  • 38,548
  • 11
  • 89
  • 102