EntityFrameworkCore: how to reverse lookup entities with ForeignKey?

asp.net-core asp.net-mvc c# entity-framework-core

Question

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)

1
0
6/13/2017 4:59:31 AM

Accepted Answer

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://docs.microsoft.com/en-us/ef/core/modeling/relationships has more info on this too.

1
6/13/2017 4:43:01 AM

Popular Answer

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);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow