MVC4使用多对多的关系保存数据 [英] MVC4 save data using Many to Many relationship

查看:195
本文介绍了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();

如何配置,所以当一个新的公司被创建,如果标签在标签表退出。不创建标记,但仍然创造了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆