实体框架视图和Linq [英] Entity Framework Views and Linq .Where

查看:173
本文介绍了实体框架视图和Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常小的实体框架设置,只包含几个相关的类/表和一个视图。我需要从这个视图中提取一个特定的记录,即我需要抓住符合两个条件的记录,它具有特定的 ProfileID 和一个具体的 QuoteID



这一行是导致问题的原因:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆