Entity Framework Views and Linq .Where

落爺英雄遲暮 提交于 2019-12-12 01:18:44

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/3709324/entity-framework-views-and-linq-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!