如何优化Linq-to-entity请求?

时间:2018-08-14 20:34:06

标签: c# optimization linq-to-entities

我有以下模型:

public class ChatMessage
{
    public int Id { get; set; }
    public string SenderUserId { get; set; }
    public string ReceiverUserId { get; set; }
    public string Message { get; set; }
    public virtual AspNetUser SenderUser { get; set; }
    public virtual AspNetUser ReceiverUser { get; set; }
}

和映射:

public class AspNetUserMap : EntityTypeConfiguration<AspNetUser>
{
    public AspNetUserMap()
    {
        this.HasKey(dp => dp.Id);
        this.Property(p => p.UserName).IsRequired().HasMaxLength(256);
        this.HasIndex(p => p.UserName).IsClustered(false).IsUnique();

        this.HasMany(e => e.OutcomingChatMessages)
            .WithRequired(e => e.SenderUser)
            .HasForeignKey(e => e.SenderUserId)
            .WillCascadeOnDelete(false);

        this.HasMany(e => e.IncomingChatMessages)
            .WithRequired(e => e.ReceiverUser)
            .HasForeignKey(e => e.ReceiverUserId)
            .WillCascadeOnDelete(false);

然后,我需要获取带有最后一条消息的用户列表,其中当前用户是正在与username进行讨论的发送者或接收者。 我有以下要求:

var usersDrivers = (from i in db.AspNetUsers
    where i.CompanyId == companyId
    && i.AspNetRoles.Any(p => p.Name == Domain.StaticStrings.RoleStaticStrings.ROLE_DRIVER)
        select new
        {
             UserId = i.Id,
             ......
             LastMessage = db.ChatMessages
             .Where(p =>
             (p.SenderUser.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase) && p.ReceiverUserId == i.Id)
             || (p.ReceiverUser.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase) && p.SenderUserId == i.Id))
             .OrderByDescending(p => p.DateTime)
             .FirstOrDefault(),
        }).ToList();

,但是此请求的执行时间很长。如何做得更好?

已添加2018年8月18日:

代码执行大约6500毫秒。以下代码具有相同的数据和相同的条件:

        var usersDrivers = (from i in _db.AspNetUsers
                            where i.CompanyId == companyId
                            && i.AspNetRoles.Any(p => p.Name == Domain.StaticStrings.RoleStaticStrings.ROLE_DRIVER)
                            select new
                            {
                                UserId = i.Id,
                                ....
                                LastMessage = _db.ChatMessages
                                   .Where(p =>
                                   (p.SenderUser.UserName.Equals(username, StringComparison.InvariantCultureIgnoreCase) && p.ReceiverUserId == i.Id)
                                   || (p.ReceiverUser.UserName.Equals(username, StringComparison.InvariantCultureIgnoreCase) && p.SenderUserId == i.Id))
                                   .OrderByDescending(p => p.DateTime)
                                   .FirstOrDefault()
                            }
                 ).ToList();

执行4500毫秒。

由于未嵌套请求,这些查询会在同一时间执行

为什么呢?

0 个答案:

没有答案