MVC4保存数据使用多对多关系 [英] MVC4 save data using Many to Many relationship
本文介绍了MVC4保存数据使用多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
许多关系
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");
}
}
添加公司
var company = new Company() { Name = "FooBar Inc" };
添加标签
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();
如何配置一个新的com pany被创建,并且标签在标签表中退出。不要创建标签,但仍然在CompanyTags表中创建关系
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
推荐答案
通过实现解决
_db.Tags.FirstOrDefault(x => x.Title == tag)
而不是做新的标签...
instead of doing new Tags...
这篇关于MVC4保存数据使用多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文