实体框架急切加载包括不工作

时间:2017-12-02 06:41:24

标签: c# entity-framework-6 eager-loading

域模型

public class InvestmentSession
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime StartDate { get; set; }

    [Required]
    public DateTime EndDate { get; set; }

    [ForeignKey("CreatedById")]
    public virtual User CreatedBy { get; set; }

    [Required]
    public int CreatedById { get; set; }

    [Required]
    public virtual Instrument Instrument { get; set; }

    public virtual ICollection<SessionUser> SessionUsers { get; set; }
}
public class SessionUser
{
    [Key, Column(Order = 1), ForeignKey("InvestmentSession")]
    public int InvestmentSession_Id { get; set; }

    [Key, Column(Order = 2), ForeignKey("User")]
    public int User_Id { get; set; }

    public virtual InvestmentSession InvestmentSession { get; set; }

    [InverseProperty("UserSessions")]
    public virtual User User { get; set; }

    public decimal? TotalProfitLoss { get; set; }
}

public class User
{
    public User()
    {

    }

    public User(string name, string email)
    {
        Name = name;
        Email = email;
        IsActive = 1;
    }

    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }

    [Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CreatedDate { get; set; }

    [Required]
    public int IsActive { get; set; }

    [JsonIgnore]
    public virtual ICollection<SessionUser> UserSessions { get; set; }

    [ForeignKey("Role_Id")]
    [JsonIgnore]
    public virtual Role Role { get; set; }

    [Required]
    public int Role_Id { get; set; }
}

我正在尝试通过Id和Include SessionUsers获取活动会话

public InvestmentSession GetActiveSession(int id)
    {
        try
        {
            var now = DateTime.UtcNow;
            return Context.InvestmentSession.Include(s => s.SessionUsers).FirstOrDefault(i => i.Id == id && now >= i.StartDate && now < i.EndDate);
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }

foreach (var sessionUser in session.SessionUsers)
            {
                var key = session.Id + sessionUser.User.Email + Constants.TRADER_PERFORMANCE_CACHE_IDENTIFIER;
                var traderPerformance = RedisStore.GetValue<TraderLivePerformanceDto>(key);
                if (traderPerformance != null)
                {
                    activeSessionData.Performances.Add(traderPerformance);
                }
                else
                {
                    var newTraderPerformance = new TraderLivePerformanceDto
                    {
                        traderId = sessionUser.User_Id,
                        traderName = sessionUser.User.Name,
                        initialCash = session.InitialCash,
                        availableCash = session.InitialCash,
                        portfolioValue = session.InitialCash
                    };
                    RedisStore.StoreValue(key, newTraderPerformance, session.EndDate);
                    activeSessionData.Performances.Add(newTraderPerformance);
                }
            }

然而迭代session.SessionUsers极其缓慢,在循环中添加断点导致代码进入预期“ ExecuteReader需要一个开放且可用的连接。连接的当前状态已关闭 “所以我假设它仍在查询DB的SessionUsers。

1 个答案:

答案 0 :(得分:0)

发现问题,在循环中访问sessionUser.User。

将我的查询更改为

return Context.InvestmentSession.Include(s => s.SessionUsers.Select(su => su.User)).FirstOrDefault(i => i.Id == id && now >= i.StartDate && now < i.EndDate);