【问题标题】:Entity Framework eager loading with include not working包含不工作的实体框架急切加载
【发布时间】:2017-12-02 06:41:24
【问题描述】:

领域模型

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 获取活动会话并包含 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 需要一个打开且可用的连接。连接的当前状态为关闭 em>”,所以我假设它仍在查询数据库中的 SessionUsers。

【问题讨论】:

  • adding a breakpoint in the loop is causing the code to go into expection 您向我们展示的代码中没有循环。
  • 您是否在其他方法中使用Context?你如何实例化它?那是单例吗?
  • 添加循环代码

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


【解决方案1】:

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

将我的查询更改为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 2012-02-07
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多