繁体   English   中英

EF CodeFirst - 添加ICollection导航属性

[英]EF CodeFirst - Adding ICollection Navigation Properties

我试图找出,如何实现导航属性到我的实体...但我的导航属性始终为null:

我已经建立了两个实体:

实体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; }

此外,我将此行包含在我覆盖的OnModelCreating-Method中:

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

我做错了什么? 我忘记了重要的事吗? 它必须如此复杂吗? 我是否必须在每个属性的覆盖方法中添加一行?

这是我的解决方案:

实体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属性,而是提到类型!

你总是说“永远”是什么意思?
如果您在尝试从DB中读取空值时谈论空值,
然后记住,当您查询上下文或使用EF延迟加载时,您需要急切地加载导航属性。

阅读本文以获取更多信息。

暂无
暂无

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

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