问题
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