0

Many to Many Relationship

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
modelBuilder.Entity<Company>()
    .HasMany(c => c.Tags)
    .WithMany(t => t.Companies)
    .Map(m =>
    {
        m.MapLeftKey("Companyid");
        m.MapRightKey("tagid");
        m.ToTable("CompanyTags");
    }
}

Add company

var company = new Company() { Name = "FooBar Inc" };

Add Tag

int tagId = _db.Tags.Where(x => x.Title == tag).Select(x => x.Id).SingleOrDefault();
if (tagId==0)
   company.Add(new Tag { Title = tag});
else
    ?????? //still create a relationship in CompanyTags (companyid,tagid)


context.Companies.Add(company);
context.SaveChanges();

How to configure so when a new company gets created and if the tag exits in the Tag table. Dont create the tag but still create the relationship in the CompanyTags table

UPDATE without if condition, if user for example adds tag title dog and if it exists a new record gets created in the tag table. Instead I want no tag to be created in the tag table just in the mapping table, see screenshot below enter image description here

Benk
  • 1,284
  • 6
  • 33
  • 64
  • 1
    See http://stackoverflow.com/questions/4253165/insert-update-many-to-many-entity-framework-how-do-i-do-it – Jasen Sep 30 '14 at 17:52

1 Answers1

0

solved by implementing

       _db.Tags.FirstOrDefault(x => x.Title == tag) 

instead of doing new Tags...

Benk
  • 1,284
  • 6
  • 33
  • 64