EF CodeFirst -添加集合导航属性

本文关键字:导航 属性 集合 添加 CodeFirst EF | 更新日期: 2023-09-27 18:16:17

我想弄清楚,如何实现导航属性到我的实体…但是我的导航属性总是空的:

我已经设置了两个实体:

实体1包含以下行:

    public int Id { get; set; }
    public ICollection<BestellterArtikel> BestellteArtikel { get; set; }

我的第二个实体是这样的:

    public int Id { get; set; }
    public int BestellungId { get; set; }
    public Bestellung BestellteArtikel { get; set; }

进一步,我将这一行包含到我的覆盖onmodelcreation - method:

    modelBuilder.Entity<Bestellung>().HasMany(e => e.BestellteArtikel).WithRequired(e => e.Bestellung);

我做错了什么?我忘了什么重要的事吗?有必要这么复杂吗?我必须在我的重写方法中为每个属性添加一行吗?

EF CodeFirst -添加集合导航属性

我的解决方案是:

实体1:

  public virtual ICollection<BestellterArtikel> BestellteArtikel { get; set; }
实体2:

  public virtual  Bestellung BestellteArtikel { get; set; }

编辑:

你还必须修改你的映射:

modelBuilder.Entity<Bestellung>().HasMany(e => e.BestellteArtikel).WithRequired(e => e.BestellteArtikel );

不是引用BestellteArtikel属性,而是引用type!

"always null"是什么意思?
如果你在谈论空值,当你试图从数据库中读取它们时,
然后记住,在查询上下文时需要急切地加载导航属性,或者使用EF惰性加载