tags:

views:

48

answers:

2

I am new to linq to sql

I wrote this function:

public ICollection<ICustomer> GetAll()
{
    DataClasses1DataContext context = new DataClasses1DataContext();
    var customers = from customer in context.Customers select customer;
    return customers.ToList().Cast<ICustomer>().ToList();
}

But it always return list of null values.

The database contain 3 records "filled with data" but this function return 3 nulls.

how to fix that?

+1  A: 

It may not be able to cast the results properly, have you made your partial Customer object implement ICustomer? If not, that is the reason.

Also you don't have to bring it to a list twice, or even once for that matter since you aren't returning a list, it might be more appropriate to change your signature to List or IEnumerable depending on your usage.

You can test whether or not the cast is succeeding by doing a simple test.

DataClasses1DataContext context = new DataClasses1DataContext();
var customers = from customer in context.Customers select customer;
int numberOfCustomers  = customers.Count();
var myCustomers = customers.Cast<ICustomer>(); //you could also do .OfType<ICustomer>();
int numberOfICustomers = myCustomers.Count();

If numberOfCustomers is 3 and numberOfICustomers is 0 then you know that was the issue.

Quintin Robinson
Re: `Cast<T>()` I made that mistake too. `Cast` will throw an exception if any of the elements can't be converted to the target type, not return null.
Rex M
@Rex I was really hoping that it would throw an exception although I haven't done any accidental casting yet with linq (if you can believe it). I'm not sure what is going on but hopefully still testing the counts at the different filtering stages will provide the op with some help.
Quintin Robinson
+1  A: 

Your problem is almost certainly at the .Cast() method (confirm this by stepping through your code & ensuring that customers is populated correctly).

Does the Customer object implement the ICustomer interface? It sounds like an obvious thing to check but that would be a likely problem.

Kirk Broadhurst
`Cast<T>` throws an exception if any of the elements can't be cast to the target type, so OP would not be seeing three nulls.
Rex M
the problem happen in the Cast, because before it everything works
Amr ElGarhy
Kirk Broadhurst
As Rex points out, the Cast is not throwing an exception so it must be 'successful' (in some sense).
Kirk Broadhurst
Please see this question to see classes headers: http://stackoverflow.com/questions/1495574/how-to-solve-this-generic-with-repository-pattern-problem
Amr ElGarhy