Lambda Expression仅在不为null且count()时由3个不同的字段分组

时间:2013-01-26 21:29:40

标签: lambda linq-to-entities grouping

这是我的模特。

public class Notification
{
    public int NotificationID { get; set; }
    public bool ReadStatus { get; set; }
    public DateTime DateCreated { get; set; }
    [ForeignKey("User"), Column(Order=0)]
    public int UserID { get; set; }
    [ForeignKey("Actor"), Column(Order = 1)]
    public int ActorID { get; set; }

    [ForeignKey("NotificationType")]
    public int NotificationTypeID { get; set; }
    //public int ObjectID { get; set; }
    [ForeignKey("Comment")]
    public int? CommentID { get; set; }
    [ForeignKey("Project")]
    public int? ProjectID { get; set; }
    [ForeignKey("Book")]
    public int? BookID { get; set; }

    public Comment Comment { get; set; }
    public Book Book { get; set; }
    public Project Project { get; set; }
    public NotificationType NotificationType { get; set; }
    public User User { get; set; }
    public User Actor { get; set; }
}

任何给定的行只有以下其中一项:BookIDProjectIDCommentID 我想获得总通知数,但我必须按NotificationType和其中一个ID对其进行分组,其他两个ID为空。可能有10个评论通知,但其中5个用于回复,5个用于另一个操作 - 但应该只是两个通知,而不是10个。

我如何编写lambda表达式来获取这些计数?

1 个答案:

答案 0 :(得分:0)

以下内容可行。

 var notificationCount = db.Notifications
      .GroupBy(x => new { x.CommentID, x.ProjectID, x.BookID, x.NotificationTypeID })
      .Count();

基于This Answer