实体框架视图和Linq [英] Entity Framework Views and Linq .Where
问题描述
这一行是导致问题的原因:
TWProfileUpchargeTotal upchargeTotals = _context.TWProfileUpchargeTotals.Where(p => p.Profileid == profile.id&& p.quoteid == _quote.quoteid)。第一();
我正在循环查看我所了解的个人资料,并从视图中获取他们的信息,因此配置文件。 ID每次更改。
此代码第一次执行时,会从视图获取正确的记录。
第二个和第三个(可能超过那个)执行时间,它检索完全相同的记录。
任何想法为什么或我做错了什么在这里?
提前谢谢
被LINQ被骗称为关闭。以下帖子(和许多其他)在SO上详细说明:
关闭
您需要做的是在上述代码中声明一个变量,并将profile.id分配给
foreach(ListOfProfiles中的配置文件)
{
var localProfile =简介;
TWProfileUpchargeTotal upchargeTotals = _context.TWProfileUpchargeTotals.Where(p => p.Profileid == localProfile.id&& p.quoteid == _quote.quoteid).First();
}
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.
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();
}
这篇关于实体框架视图和Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!