abolotnov
abolotnov

Reputation: 4332

EntityFrameworkCore: how to reverse lookup entities with ForeignKey?

When I have two entities:

public class Org : BaseEntity, IEntityBase
    {
        public string Name { get; set; }
    }

public class Portfolio : BaseEntity, IEntityBase
    {
        public string Name { get; set; }
        public int OrganizationId { get; set; }

        [ForeignKey("OrganizationId")]
        public virtual Org Organization { get; set; }
        public bool IsPrivate { get; set; }
    }

When I retrieve Portfolio data inside web api controller, I can do: dbSet.Include(a=>a.Organization) to load the related Org data. Is there a way to "reverse" this lookup from within the Org (to load all Portfolio that have foreignkeys to the Org being looked at)?

When I add a List<Portfolio> Portfolios {get;set;} property, I run into the loop reference endless loop: I assume because the two entities cross-reference each other.

The way I retrieve the data is this:

public virtual IEnumerable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = _context.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query.AsEnumerable();
    }

OrgRepo.AllIncluding(a=>a.Portfolios)

Upvotes: 1

Views: 2508

Answers (2)

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

Example:

   public class Org : BaseEntity, IEntityBase
    {
        public string Name { get; set; }
        public ICollection<Portfolio> Portfolios  { get; set; }
    }

    public class Portfolio : BaseEntity, IEntityBase
    {
        public string Name { get; set; }
        public int OrganizationId { get; set; }

        [ForeignKey("OrganizationId")]
        public virtual Org Organization { get; set; }
        public bool IsPrivate { get; set; }
    }

Use:

var orgs= _context.Portfolios.Include(a=>a.Organization).select(s=>s.Organization);
var portfolios= _context.Orgs .Include(a=>a.Portfolios).SelectMany(s=>s.Portfolios);

Upvotes: 0

Max
Max

Reputation: 137

It should be as easy as adding a list of Portfolio to Org.

public class Org : BaseEntity, IEntityBase
{
    public string Name { get; set; }
    public List <Portfolio> Portfolios  { get; set; } //Note, the naming should be plural, to indicate one to many
}

https://learn.microsoft.com/en-us/ef/core/modeling/relationships has more info on this too.

Upvotes: 1

Related Questions