简体   繁体   English

实体框架使用LEFT JOIN语句为视图返回错误数据

[英]Entity Framework returns wrong data for view with LEFT JOIN statement

I'm experiencing strange behavior of Entity Framework. 我遇到了Entity Framework的奇怪行为。 EF-generated DbContext object returns data different from the actual data in database. EF生成的DbContext对象返回与数据库中的实际数据不同的数据。

Consider the following DB schema: 请考虑以下数据库架构: 数据库架构

Letter data: Letter数据:

Id      Value   LanguageId
------- ------- ----------
1       A       1
2       A       2
3       B       1
4       B       2

Language data: Language数据:

Id      Value
------- -------
1       English
2       Russian

I also have the following simple view LetterLanguageView . 我还有以下简单的LetterLanguageView视图。 Note that it uses LEFT JOIN clause because Letter.LanguageId could be NULL : 请注意,它使用LEFT JOIN子句,因为Letter.LanguageId可能为NULL

SELECT dbo.Letter.Value as Letter, dbo.Language.Value as Language
FROM dbo.Letter
LEFT JOIN dbo.Language ON dbo.Letter.LanguageId = dbo.Language.Id

The result of this view is pretty straightforward: 这个视图的结果非常简单:

Letter  Language
------- --------
A       English
A       Russian
B       English
B       Russian

However, when I use this view from Entity Framework, I have the following results: 但是,当我从Entity Framework使用此视图时,我得到以下结果:

错误的数据

As you can see, the Language property is wrong, there is no Russian language at all. 如您所见, Language属性是错误的,根本就没有俄语。

If you are wondering, here is the code snippet for reading this data: 如果您想知道,这是用于读取此数据的代码段:

using (var e = new TestEntities())
{
    var data = e.LetterLanguageView;
}

Nothing special, no conversions or any modifications of returned data, so it looks like the problem is in the Entity Framework itself. 没有什么特别的,没有转换或对返回数据的任何修改,所以看起来问题出在实体框架本身。

Could you suggest any ideas why EF returns wrong data in this case and how could I fix this? 你能否提出任何想法,为什么EF在这种情况下会返回错误的数据?我该如何解决这个问题?

Make sure in your EF model for LetterLanguageView that you set Letter and Language as EntityKey = true. 在您的EF模型中确保LetterLanguageView将Letter和Language设置为EntityKey = true。

Another trick I have used in the past is add a row Id column and make that the PK. 我过去使用的另一个技巧是添加一行Id列并使其成为PK。 Here is someones (not me) blog about it 这是关于它的某人(不是我)的博客

http://girlfromoutofthisworld.com/entity-framework-and-setting-primary-keys-on-views/ http://girlfromoutofthisworld.com/entity-framework-and-setting-primary-keys-on-views/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM