【问题标题】:MVC4 save data using Many to Many relationshipMVC4 使用多对多关系保存数据
【发布时间】: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 并且如果它存在,则在标签表中创建一条新记录。相反,我不希望仅在映射表中的标签表中创建标签,请参见下面的屏幕截图

【问题讨论】:

标签: entity-framework asp.net-mvc-4 ef-code-first many-to-many


【解决方案1】:

通过实施解决

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

而不是做新标签...

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多