无效的强制转换异常:尝试使用linq-sql连接两个表

时间:2014-09-18 06:50:48

标签: c# linq join

我正在尝试使用他们的共同ID(MOTHERID)加入两个表。但他下面的代码工作正常,但在某些时候,它开始在:

抛出“无效的强制转换异常”
 var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();

我认为异常是由toList()转换引起的,因为当我删除.ToList()时它工作正常但我需要使用它来使其余的代码正常工作。以下是代码的一部分:

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();

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在下面的行中尝试var的特定类型替换:

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

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();

它是假的,我希望它可以帮助你