LINQ查询返回第一个结果的多个副本 [英] LINQ Query returns multiple copies of first result
问题描述
我在数据库中定义了一个视图(archiveContentPreviews),它将多个表连接在一起,并且在Linq中它具有一个实体键(ArchiveID),我想通过以下简单查询来查询该视图:
I have a view defined in the database (archiveContentPreviews), It joins together several tables and in Linq it has one entity key (ArchiveID), I want to query this view with this simple query:
var x = from fields in entities2.archiveContentPreviews
where fields.ArchiveID == archiveID
select fields;
return x.ToList<archiveContentPreview>();
它返回准确数量的结果,但是第一个结果有多个副本的问题,当我在SQL Management Studio中执行该查询时,它返回正确的结果,有帮助吗?!
The problem that it returns exact number of results but multiple copy of the first result, and when I execute that query in SQL management studio it returns correct results, any help?!
推荐答案
通常,当指定为主键的一个或多个列在视图中没有唯一值时,会发生这种情况.在您的情况下,ArchiveID
可能会在大量视图行中重复(这也由您的where
子句指示).您将必须找到(或添加到视图中)唯一标识视图行并将其标记为EF模型中的主键的列的组合.
This typically happens when the column (or columns) designated as primary key have no unique values in the view. In your case, ArchiveID
is probably repeated in a large number of view rows (which is also indicated by your where
clause). You will have to find (or add to the view) a combination of columns that uniquely identify a view row and mark those as primary key in the EF model.
请注意,所生成的SQL查询返回的数据可能包含具有不同值(但相同的ArchiveID
)的行,但是EF只是为每个ArchiveID
实例化实体对象,并为其找到该ID的第一个结果.
Note that the data returned by the generated SQL query may contain rows with different values (but the same ArchiveID
), but EF just materializes entity objects for each ArchiveID
with the first result it can find for that id.
这篇关于LINQ查询返回第一个结果的多个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!