EntityFrameworkCore:如何使用ForeignKey反转查找实体?

时间:2017-06-13 04:33:34

标签: c# asp.net-mvc asp.net-core entity-framework-core

当我有两个实体时:

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)

2 个答案:

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