简体   繁体   English

实体框架中的多对多关系

[英]Many to many relationship in Entity Framework

I set up a many to many relationship like this (removing all the irrelevant properties): 我建立了这样的多对多关系(删除了所有不相关的属性):

public class Makes
{
  [Key]
  public int MakeId { get; set; }

  public ICollection<KeyWords> KeyWords {get; set;}
}

public class KeyWords 
{
   public KeyWords()
   {
       Makes = new HashSet<Makes>();
   }

   [Key]
   public int KeyWordsId { get; set;}
   public string KeyWord { get; set;}
}

And then in the context definition: 然后在上下文定义中:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<KeyWords>().HasMany(w => w.Makes).WithMany(kw => kw.KeyWords).Map(
           m =>
           {
                m.MapLeftKey("KeyWords_KeyWordsID");
                m.MapRightKey("Makes_MakesID");
                m.ToTable("MakesKeyWords");
            });

        base.OnModelCreating(modelBuilder);
    }

When I step through the database seeding, it looks like the entity is created correctly when I create some Makes and create some key words and then add some keywords to the makes. 当我逐步进行数据库播种时,当我创建一些Makes并创建一些关键字,然后向makes中添加一些关键字时,似乎正确地创建了实体。 I'm able to navigate between the two entities just fine using the watch. 我可以使用手表在两个实体之间导航。

After the database initialization is complete, I look at the database and it looks like all of the data is there. 数据库初始化完成后,我查看数据库,看起来所有数据都在那里。 However, when I go to actually display the keywords in the view, the Makes that I KNOW I assigned a keyword to have a count of 0: 但是,当我实际在视图中显示关键字时,“使我知道的信息”使关键字的计数为0:

@if (Model != null)
{
    Foreach(models.Makes item in model.Makes)
    {
        if (item.KeyWords.Count > 0) 
                {
                    <div class="KeyWords">
                    @foreach (Models.KeyWords kw in item.KeyWords)
                    {
                        <span class="KeyWord">@kw.KeyWord</span>
                    }
                    </div>
                }
     }
}

Nothing happens, the keywords aren't being associated with the makes anymore. 没有任何反应,关键字不再与品牌相关联。

What am I missing? 我想念什么?

Thanks! 谢谢!

Either mark your navigation property as virtual to enable lazy loading ... 将您的导航属性标记为virtual以启用延迟加载 ...

public virtual ICollection<KeyWords> KeyWords {get; set;}

...or use Include when you load the makes ( eager loading ): ...或在加载品牌时使用Include热切加载 ):

var makes = context.Makes.Include(m => m.KeyWords).ToList();

(You need using System.Data.Entity; in your code file for the lambda version of Include .) (您需要在代码文件中使用Lambda版本的Include using System.Data.Entity;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM