Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply the LINQ to SQL Distinct() operator to a List<T>?

I have a serious(it's getting me crazy) problem with LINQ to SQL. I am developing an ASP.NET MVC3 application using c# and Razor in Visual Studio 2010.

I have two database tables, Product and Categories:

Product(Prod_Id[primary key], other attributes)

Categories((Dept_Id, Prod_Id) [primary keys], other attributes)

Obviously Prod_Id in Categories is a foreign key. Both classes are mapped using the Entity Framework (EF). I do not mention the context of the application for simplicity.

In Categories there are multiple rows containing the Prod_Id. I want to make a projection of all Distinct Prod_Id in Categories. I did it using plain (T)SQL in SQL Server MGMT Studio according to this (really simple) query:

SELECT DISTINCT Prod_Id
FROM Categories

and the result is correct. Now I need to make this query in my application so I used:

var query = _StoreDB.Categories.Select(m => m.Prod_Id).Distinct();

I go to check the result of my query by using:

query.Select(m => m.Prod_Id);

or

foreach(var item in query)
{
  item.Prod_Id;
  //other instructions
}

and it does not work. First of all the Intellisense when I attempt to write query.Select(m => m. or item.shows just suggestions about methods (such as Equals, etc...) and not properties. I thought that maybe there was something wrong with Intellisense (I guess most of you many times hoped that Intellisense was wrong :-D) but when I launch the application I receive an error at runtime.

Before giving your answer keep in mind that;

  1. I checked many forums, I tried the normal LINQ to SQL (without using lambdas) but it does not work. The fact that it works in (T)SQL means that there is something wrong with the LINQ to SQL instruction (other queries in my application work perfectly).

  2. For application related reasons, I used a List<T> variable instead of _StoreDB.Categories and I thought that was the problem. If you can offer me a solution without using a List<T> is appreciated as well.

like image 873
CiccioMiami Avatar asked Apr 19 '11 13:04

CiccioMiami


1 Answers

This line:

var query = _StoreDB.Categories.Select(m => m.Prod_Id).Distinct();

Your LINQ query most likely returns IEnumerable... of ints (judging by Select(m => m.Prod_Id)). You have list of integers, not list of entity objects. Try to print them and see what you got.

like image 197
k.m Avatar answered Sep 18 '22 10:09

k.m