简体   繁体   中英

EF CodeFirst - Adding ICollection Navigation Properties

I'm trying to figure out, how to implement navigation properties to my entities... But my navigation properties is always null:

I've set up two entities:

Entity 1 contains this lines:

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

My second entity looks like this:

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

Further more I included this line to my overwritten OnModelCreating-Method:

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

What have I done wrong? Have I forgotten something important? And does it has to be so complex? Do I have to add a line in my overwritten method for each property?

Here is my solution :

Entity 1:

  public virtual ICollection<BestellterArtikel> BestellteArtikel { get; set; }

Entity 2:

  public virtual  Bestellung BestellteArtikel { get; set; }

Edited:

also you have to revise your mapping:

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

Instead of referring to BestellteArtikel property, you referred to type!

What do you mean by "always null"?
If you are talking about null values when you try to read them from DB,
then remember that you need to eagerly load the navigation properties when you query the context, or use EF lazy-loading.

Read this for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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