afom
afom

Reputation: 61

Invalid cast exception: trying to join two tables using linq-sql

I'm trying to join two tables using their common id which is MOTHERID. But he code below was working fine but at some point it starts throwing "Invalid cast exception" at:

 var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();

I think the exception is being caused by the toList() conversion because when I remove .ToList() it works fine but I need to use that for the rest of the code to work properly. Here is some part of the code:

MaternalVisitData _maternalvisitvaluedb =
new  MaternalVisitData(MaternalVisitData.strConnectionString);
MaternalCareData _maternalcarevaluedb = 
new MaternalCareData(MaternalCareData.strConnectionString);

var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();
var secondQuery = (from t in _maternalcarevaluedb.Value select t).ToList();

var result = (from s in firstQuery
join k in secondQuery
on s.MotherId equals k.MotherId
where (DateTime)s.SecondVisit.Date == DateTime.Now.Date 
select s).ToList();

Thanks for your help!

Upvotes: 0

Views: 189

Answers (1)

Nima Derakhshanjan
Nima Derakhshanjan

Reputation: 1402

try specific type alternate of var in below lines :

var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();
var secondQuery = (from t in _maternalcarevaluedb.Value select t).ToList();

like this :

List<maternalvisitvaluedb> firstQuery = (list<maternalvisitvaluedb>)(from s in _maternalvisitvaluedb.Value select s).ToList();
List<maternalcarevaluedb> secondQuery = (List<maternalcarevaluedb>)(from t in _maternalcarevaluedb.Value select t).ToList();

it's a pseudo , I hope it helps you

Upvotes: 1

Related Questions