与EF Core一起使用包含时,导航属性始终为null

时间:2019-08-02 13:24:56

标签: .net-core entity-framework-core

我有这些实体:

...
render() {
  <div>
    <button onClick={() => this.props.history.push({ hash: 'send-me-an-email' })}>
      Send me and email
    </button>
    <Popin 
      isOpened={this.state.isPopinOpened} 
      handleClose={() => this.props.history.push({ hash: '' })} />
  </div>
}
...

并具有如下所示的存储库方法:

public class Portfolio : EntityBase<int>
{
    public string Name { get; set; }

    public virtual Client Client { get; set; }
    public Guid ClientId { get; set; }
}

public class Client : EntityBase<Guid>
{
    public string Name { get; set; }

    public virtual ICollection<Portfolio> Portfolios { get; set; }
}

但是当我调用SearchPortfolios时,Portfolio上的Client导航属性始终为null:

private readonly EnisDbContext _enisDbContext;

public IEnumerable<Portfolio> SearchPortfolios(Expression<Func<Portfolio, bool>> criteria, bool includeClients = false)
{
    IQueryable<Portfolio> portfolios = _enisDbContext.Portfolios;
    if (includeClients)
    {
        portfolios.Include(c => c.Client);
    }

    return portfolios.Where(criteria);
}

在我的应用程序中的其他地方,我已经以类似的方式使用.include()了,但是效果很好。我正在将EF Core 2.2.4与SQL Server一起使用。

1 个答案:

答案 0 :(得分:2)

portfolios.Include(c => c.Client);

这应该是

portfolios = portfolios.Include(c => c.Client);

如果不将其分配给当前的投资组合查询,则不会将.include保留在其中