0

以下 LINQ to Entities 查询从电子邮件中获取所有链接点击,按 URL 对它们进行分组并将它们投影到模型中。

期望的最终结果将类似于:

Clicks  |  URL     |  Clickers
-------------------------------------------------------------------------------------
2          x.com      User 1, User 2...
1          y.com      User 1

我有一个对象CampaignEmailRecipient,其中包含单击该链接的所有用户,我还想将其包含在我的模型中的 property 中Clickers

我只是不确定如何在我的小组到位的情况下正确执行此操作,并想知道是否有人可以提供帮助?

我的模型

public class CampaignEmailReportLinksViewModel
{
    public int Id { get; set; }
    public int CampaignElementId { get; set; }
    public string LinkURL { get; set; }
    public int QtyClicks { get; set; }
    public CampaignEmailRecipient Clickers { get; set; }
}

我的查询

public List<CampaignEmailReportLinksViewModel> GetCampaignLinksByElementId(int id, int cid, string user)
{
    var items = (from t1 in db.CampaignLinkClicks
                    where
                        (t1.CampaignLink.CampaignElementId == id) &&
                        (t1.CampaignLink.CampaignElement.Campaign.CompanyId == cid)

                    group new {t1} by new
                                        {
                                            t1.CampaignLink.URL,
                                            t1.CampaignLink.CampaignElementId
                                        }
                    into g

                    select new CampaignEmailReportLinksViewModel
                            {
                                LinkURL = g.Key.URL,
                                QtyClicks = g.Count(),
                                Clickers = ???????????
                            }).OrderByDescending(x => x.QtyClicks).ToList();

    return items.ToList();
}

编辑

CampaignLinkClick 如下所示:

public int Id
public int CampaignRecipientId
public string IP
public datetime Timestamp
public int CampaignLinkId
4

1 回答 1

1

如果您考虑您正在尝试做什么,您的 SQL 将按 URL 对项目进行分组,所以如果您有:

User  |  URL     
--------------------------------------------------
User1          x.com      
User2          x.com      
User1          y.com   

当您按 URL 分组时,您将获得一个结果集,因此 user 的子元素将丢失,因此,

URL     
--------------------------------------------------
x.com      
y.com     

一种(相当昂贵的)方法是获取每个 URL 的结果,

select new CampaignEmailReportLinksViewModel
                            {
                                LinkURL = g.Key.URL,
                                QtyClicks = g.Count(),
                                Clickers = ""
                            }

foreach(var item in items){
    item.Clickers = db.CampaignLinkClicks
                           .Where(x=>x.Url == item.URL)
                           .Clickers.Select(x=>x.Name).ToString();
}
于 2012-07-03T14:53:08.430 回答