MVC4 save data using Many to Many relationship

可紊 提交于 2019-12-04 07:03:54

问题


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


回答1:


solved by implementing

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

instead of doing new Tags...



来源:https://stackoverflow.com/questions/26092567/mvc4-save-data-using-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!