0

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.

4

1 回答 1

3

您被称为闭包的 LINQ“陷阱”所困扰。关于 SO 的以下帖子(以及许多其他帖子)详细说明了这一点: 关闭

您需要做的是在您从上述代码中省略的 foreach 中声明一个变量,并将 profile.id 分配给它并在 Where 子句中使用它。

foreach(Profile profile in ListOfProfiles)
{
    var localProfile = profile; 
    TWProfileUpchargeTotal upchargeTotals = _context.TWProfileUpchargeTotals.Where(p => p.Profileid == localProfile.id && p.quoteid == _quote.quoteid).First();
}
于 2010-09-14T14:49:38.160 回答