GrahamJRoy
GrahamJRoy

Reputation: 1643

One-to-Many EF .NET Core Relationship Not Working

I have a .net core api application which includes EF to retrieve data. I have set up a data context and I can map tables from the db fine. When I try and set up a relationship though I am always getting a null back for the nested object.

I have an 'Opportunity' class which contains an ICollection of 'Notes'

public class Opportunity
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
    public decimal FinalDealProfit { get; set; }
    public ICollection<CRMNote> CRMNotes { get; set; }
}

and a Note class that references the opportunity:

public class CRMNote
{
    public int Id { get; set; }
    public int OpportunityId { get; set; }
    public string Note { get; set; }
    public string User { get; set; }
    public DateTime DateTime { get; set; }
    public string FilePath { get; set; }
    public Opportunity Opportunity { get; set; }
}

In my context class have the following set up:

modelBuilder.Entity<Opportunity>(entity =>
  {
    entity.ToTable("CRM_Opportunity");
    entity.HasMany<CRMNote>(n => n.CRMNotes)
      .WithOne(t => t.Opportunity)
      .HasForeignKey(k => k.OpportunityId);
    });

and I have also been mapping the Note class:

modelBuilder.Entity<CRMNote>(entity =>
  {
    entity.ToTable("CRM_Note");
    //entity.HasOne<Opportunity>(t => t.Opportunity)
    //    .WithMany(p => p.CRMNotes)
    //    .HasForeignKey(k => k.OpportunityId);
  });

as you can see I have been playing around with how to connect the entities together.

Whenever I retrieve the opportunity though the notes array is always null. I have tried putting an empty constructor on the Opportunity class:

public Opportunity()
  {
    CRMNotes = new List<CRMNote>();
  }

but this just means I get an empty array rather than a null.

I can't see what I have missed. I have checked the docs for it:

https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx

but clearly I have missed something. Any help greatly appreciated as this should be an easy task but something is clearly eluding me.

Upvotes: 0

Views: 538

Answers (1)

vahid tajari
vahid tajari

Reputation: 1303

There are three common O/RM patterns used to load related data Eager loading, Explicit loading and Lazy loading

For example, in eager loading you can use:

var opportunities=context.opportunities.Include(opportunity=>opportunity.CRMNotes).ToList()

Upvotes: 1

Related Questions