Operation could destabilize the runtime
I was trying to reproduce Repository pattern that Rob Conery was using in his MVC Store Front project in my own project.
Continuing with the interface programming style hype, I decided to make everything implement some sort of an interface. So my domain object (say Person), will implement IPerson interface and so on.
So I have an IPersonRepository that will have a couple of implementations. One for testing (TestPersonRepository : IPersonRepository) and a real Linq To Sql implmentation (SqlPersonRepository : IPersonRepository).
The repository has one method, which is IQueryable<IPerson> GetPersons() that will return all the available persons.
My test which was using the TestPersonRepository implementation works well. But when I tried integrating my code using the real Linq to Sql implementation, it blew up.
The code for the SqlPersonRepository implementation is as follow:
1: public IQueryable<IPerson> GetPersons()
2: { 3: var db = new Data.Linq.SampleDbContext();
4:
5: var query = from p in db.Persons
6: select (IPerson) new Domain.Person { 7: FirstName = p.FirstName, LastName = p.LastName
8: };
9:
10: return query;
11: }
As you can see, I was trying to cast Person to IPerson in the Linq query. This apparently didn't work. Hehehe. Changing all my interface to IQueryable<Person> and removing the casting will make it work.
Another work around that I found to work is using the following code:
1: public IQueryable<IPerson> GetPerson()
2: { 3: var db = new Data.Linq.SampleDbContext();
4:
5: var query = from p in db.Persons
6: select p;
7:
8: IList<IPerson> results = new List<IPerson>();
9:
10: foreach(var p in query)
11: { 12: results.Add(new Domain.Person { FirstName = p.FirstName, LastName = p.LastName }); 13: }
14:
15: return results.AsQueryable();
16: }
Sucks :)
Anyone want to take a stab at what's going on here?