LINQ Query returns multiple copies of first result

别来无恙 提交于 2020-01-11 09:35:47

问题


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

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


回答1:


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.

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.




回答2:


Note a workaround (if you can't specify additional keys -- e.g. for a datatable you don't administer but just read-only access or whatever) is to select the individual columns within the query.

var x = from fields in entities2.archiveContentPreviews
                where fields.ArchiveID == archiveID
                select new {fields.col1, fields.col2};
        return x.ToList<archiveContentPreview>();


来源:https://stackoverflow.com/questions/14811050/linq-query-returns-multiple-copies-of-first-result

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