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