I have a one to many relationship between campaigns
and campaign stats
. A campaign stat item can have at most one entry in the database for a campaign for a single day.
So starting from 9/20/13 - DateTime.Now
get campaigns
where there isn't a related campaign stat
, but I also want to get the actual date that the stat is missing from
I'd like to display for instance campaign name
, stat date
(that is missing). I'm having a hard time coming up with a solution to this, but I've written this code to start.
var fromDate = new DateTime(2013, 9, 20);
var toDate = DateTime.Now;
var dates = Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
.Select(d => fromDate.AddDays(d));
var a = from c in _db.Campaigns
join s in _db.CampaignStats on c.Id equals s.CampaignId into s1
from s in s1.DefaultIfEmpty()
where s == null
select new {c, s};
Sample output would be: (Campaign 1 has stats for 9/20/2013 and 9/22/2013)
`Campaign 1 9/21/2013`
`Campaign 1 9/23/2013`
`Campaign 1 9/24/2013`
`...`
Edit
Using Bob's answer I formed this LINQ query:
(from counts in
(from cal in _db.CalendarMonths
from c in _db.Campaigns
let statCount = (from s in _db.CampaignStats
where s.CampaignId == c.Id
where s.Date == cal.date
group s by s.Id into s1
select s1.Count()).FirstOrDefault()
select new
{
cal.date,
c.Id,
statCount
})
where counts.statCount == 0
select new
{
counts.Id,
counts.date,
});