abolotnov abolotnov -4 years ago 138
C# Question

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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download