LINQ query returns multiple copies of the first result
I have a view defined in a database (archiveContentPreviews), it joins multiple tables, and in Linq 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 is that it returns the exact number of results, but multiple copies of the first result, and when I execute this query in SQL management studio it returns correct results, any help ?!
source to share
This usually occurs when the column (or columns) designated as the primary key does not have unique values ββin the view. In your case ArchiveID
, it is probably repeated across a lot of lines of the view (which is also pointed out in the sentence where
). You will need to find (or add to the view) a combination of columns that uniquely identify the row of the view and mark them as the 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 will simply materialize entity objects for each ArchiveID
with the first result it can find for that id.
source to share
Note the workaround (if you cannot provide additional keys - for example, for data that you don't administer, but just read-only access, or whatever) - select individual columns in the query.
var x = from fields in entities2.archiveContentPreviews
where fields.ArchiveID == archiveID
select new {fields.col1, fields.col2};
return x.ToList<archiveContentPreview>();
source to share