如何使用lambdas进行Linq to SQL查询并包含更快的内容?

时间:2015-10-23 17:48:49

标签: c# sql linq lambda

我有这段代码执行得很差,并因此导致网页加载延迟。查询底层的对象并不过分复杂,我在时间条目表中只有大约6,000行,并且在包含的表中只有少量行。

如何重新编写它以提高效率?为什么这么慢?它是多重包含,lambdas还是ToList()?当我删除ToList()时它很快,但是此查询后面的代码需要一个时间条目列表,所以我想找到一个更快的替代方案,它仍会返回一个列表。

var timeEntries = db.TimeEntries
    .Include(t => t.Assignment)
    .Include(t => t.TimeStatus)
    .Include(t => t.User)
    .Where(t => t.UserID == strCurrentUserId)
    .Where(t => t.TimeDate >= wcDate && t.TimeDate <= sundayDate)
    .OrderBy(t => t.TimeDate)
    .ToList(); 

下面列出了一些类(但是,我没有暴露我的用户类):

public class TimeEntry
{
    [Key]
    public int ID { get; set; }

    public int AssignmentID { get; set; }
    public virtual Assignment Assignment { get; set; }
    public DateTime TimeDate { get; set; }
    public decimal TimeUsed { get; set; }
    public int TimeStatusID { get; set; }
    public TimeStatus TimeStatus { get; set; }
    public string UserID { get; set; }
    public virtual User User { get; set; }
    [DataType(DataType.MultilineText)]
    public string Comment { get; set; }
}

public class TimeStatus
{
    [Key]
    public int ID { get; set; }
    public string Status { get; set; }
}

public class Assignment
{
    [Key]
    public int ID { get; set; }
    public int ProjectID { get; set; }
    public virtual Project Project { get; set; }
    public string UserID { get; set; }
    public virtual User User { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int AssignmentStatusID { get; set; }
    public AssignmentStatus AssignmentStatus { get; set; }
    public decimal ChargeRate { get; set; }
    public int MaxDays { get; set; }
    public bool Billable { get; set; }
    public bool BillableInternal { get; set; }

    [Display(Name = "Assignment No.")]
    public string AssignmentNumber
    {
        get
        {
            return "A" + ID.ToString("D5");
        }
        set { }
    }
}

0 个答案:

没有答案