如何在LINQ中获得一个类的属性

时间:2018-03-13 14:33:24

标签: c# database linq lambda

我正在尝试使用linq查找未读消息。我正在计算消息的最后修改日期是否大于用户的LastViewedOn日期。 My ConversationMembers类具有LastViewedOn属性。但我找不到一种方法来达到用户的LastViewedOn属性..

.Count(x => x.ConversationMembers
            .Where(y => y.MembershipId.Value == membershipId)
            .Any(y => y.LastViewedOn == null)
            ||
            x.ConversationMessages.OrderByDescending(message => message.LastModifiedOn)
        .Any(z => z.LastModifiedOn > x.ConversationMembers
        .Where(y => y.MembershipId.Value == membershipId) 
        .Select()
        .LastViewedOn.Value
    )); //here i m trying to reach LastViewedOn value but it not work

请问我能帮助我如何达到这个价值?

这是我的ConversationMember课程

public class ConversationMember
{
    public Guid Id { get; set; }
    public Guid ConversationId { get; set; }
    public virtual Conversation Conversation { get; set; }
    public Guid? MembershipId { get; set; }
    public DateTime? LastViewedOn { get; set; }
}

这里是ConversationMessage类

 public class ConversationMessage
    {
        public Guid Id { get; set; }
        [Required]
        public string Text { get; set; }
        public Guid ConversationId { get; set; }
        public virtual Conversation Conversation { get; set; }
        public Guid? MembershipId { get; set; }

        [Required]
        [Column(TypeName = "datetime2")]
        public DateTime LastModifiedOn { get; set; }
    }

在这里谈话课

public class Conversation
{
    public Guid Id { get; set; }

    public virtual ICollection<ConversationMember> ConversationMembers { get; set; }
    public virtual ICollection<ConversationMessage> ConversationMessages { get; set; }


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

1 个答案:

答案 0 :(得分:1)

尝试将LINQ更改为:

.Count(x => x.ConversationMembers.Where(y => y.MembershipId.Value == membershipId)
    .Any(y => y.LastViewedOn == null) || x.ConversationMessages.OrderByDescending(message => message.LastModifiedOn)
    .Any(z => z.LastModifiedOn > x.ConversationMembers.FirstOrDefault(y => y.MembershipId.Value == membershipId).LastViewedOn.Value));