【发布时间】:2014-09-29 04:27:42
【问题描述】:
多对多关系
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();
如何在创建新公司以及标签是否存在于标签表中时进行配置。不要创建标签,但仍然在 CompanyTags 表中创建关系
更新 没有 if 条件,如果用户例如添加标签标题 dog 并且如果它存在,则在标签表中创建一条新记录。相反,我不希望仅在映射表中的标签表中创建标签,请参见下面的屏幕截图
【问题讨论】:
-
非常感谢@Jasen 的链接。
标签: entity-framework asp.net-mvc-4 ef-code-first many-to-many