当我有两个实体时:
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; }
}
当我在web api控制器中检索Portfolio数据时,我可以执行:dbSet.Include(a=>a.Organization)
来加载相关的Org
数据。有没有办法反转"从Org内部查找(将所有具有外键的Portfolio
加载到正在查看的Org中)?
当我添加List<Portfolio> Portfolios {get;set;}
属性时,我会遇到循环引用无限循环:我假设因为这两个实体相互交叉引用。
我检索数据的方式是:
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)
答案 0 :(得分:1)
这应该像向组织添加投资组合列表一样简单。
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也有更多信息。
答案 1 :(得分:0)
示例:
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; }
}
使用:强>
var orgs= _context.Portfolios.Include(a=>a.Organization).select(s=>s.Organization);
var portfolios= _context.Orgs .Include(a=>a.Portfolios).SelectMany(s=>s.Portfolios);