views:

32

answers:

1

I have a very small entity framework setup containing only a few related classes/tables and a view. I need to be able to pull a specific record from this view, namely, I need to be able to grab the record that meets two criteria, it has a specific ProfileID and a specific QuoteID.

This line is what's causing the problem:

TWProfileUpchargeTotal upchargeTotals = _context.TWProfileUpchargeTotals.Where(p => p.Profileid == profile.id && p.quoteid == _quote.quoteid).First();

I'm looping through the profiles I know about and getting their information from the view, so profile.id changes each time.

The first time this code executes it gets the correct record from the view. The second and third (and presumably beyond that) time it executes, it retrieves the exact same record.

Any idea why or what I'm doing wrong here?

Thanks, in advance.

+2  A: 

You've been bitten by the LINQ "gotcha" called closure. The following post (and many others) on SO detail this: closure

What you need to do is declare a variable WITHIN the foreach you've ommited from the above code and assign the profile.id to this and use this in the Where clause.

foreach(Profile profile in ListOfProfiles)
{
    var localProfile = profile; 
    TWProfileUpchargeTotal upchargeTotals = _context.TWProfileUpchargeTotals.Where(p => p.Profileid == localProfile.id && p.quoteid == _quote.quoteid).First();
}
Daz Lewis
Thanks! It's an interesting concept that I'll definitely have to read up on. Something new every day, ya know.
Anthony Compton