以下LINQ to Entities查询从电子邮件中获取所有链接点击,按URL对其进行分组并将其投影到模型中。
期望的最终结果如下:
Clicks | URL | Clickers
-------------------------------------------------------------------------------------
2 x.com User 1, User 2...
1 y.com User 1
我有一个对象CampaignEmailRecipient
,其中包含点击该链接的所有用户,我还希望将其包含在我的模型中的属性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
答案 0 :(得分:1)
如果你考虑一下你要做什么,你的SQL会按URL分组项目,所以如果你有:
User | URL
--------------------------------------------------
User1 x.com
User2 x.com
User1 y.com
当您按URL分组时,您将获得一个结果集,因此用户的子元素将会丢失,因此,
URL
--------------------------------------------------
x.com
y.com
一种(相当昂贵的)方式是获取每个网址的结果,
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();
}