2

I'm somewhat new to Entity Framework (4). I've been tracking down a bug in our software, and I've nailed it down the follow quirk. I'm curious if anyone can help me explain why these two Counts (dataCount and data2Count) would be different depending on the way I've invoked them. data2Count is correct and actually matches up with what I have in SQL.

        using (var context = new Entities(ConnectionString))
        {
            var startDateTime = DateTime.Parse("10/1/2011");
            var endDateTime = DateTime.Parse("12/31/2011 23:59");

            var query = from data in context.vDATA
                        where data.ParentId == parentId &&
                        data.TimeStamp >= startDateTime &&
                        data.TimeStamp <= endDateTime
                        select data;

            var data = query.ToList();
            var dataCount = data.Where(x => x.TestType == 20).Count();
            //dataCount is 162

            var data2 = query.Where(x => x.TestType == 20);
            var data2Count = data2.Count();
            //data2Count is 198
        }

Thanks.

John Russell
  • 2,177
  • 4
  • 26
  • 47

2 Answers2

1

Alright, I think I found and fixed what was happening - although I'm not sure I can explain internally how EF handles it... I found an article here: Entity framework result discrepancy for a database views that sounded like a similar issue. My data in SQL had several records who's fields were roughly identical. The only distinguishing field was TestType. But it was NOT marked as part of the key. Simply extending the key to include this field caused the Counts to match up correctly.

Community
  • 1
  • 1
John Russell
  • 2,177
  • 4
  • 26
  • 47
0

How is parentId getting set? Is it a variable declared outside of a loop this code fragment is running in? If so, this might be acting funky because of closure issues. This other question gives you a lot of information on how to address the closure issues.

Community
  • 1
  • 1
Jeff Siver
  • 7,434
  • 30
  • 32
  • Thanks for the feedback. That's a great thought; however, I can use a constant value (e.g. data.ParentId == 129), and I still get the same result. Also, there are no loops, so I don't think closure is the issue. – John Russell Jan 21 '12 at 12:06