从 SQL 创建 LINQ
Creating LINQ from SQL
我正在尝试根据 Sql 创建 Linq 查询,但无法使其正常工作。
SQL
"select distinct(roomName) as RoomName, tblroomid as RoomId
from TblMaster,tblrooms
where tblrooms.tblroomid = TblPresentationMaster.tblroomid
and convert(datetime, PDay, 101)='" + Pday + "'";
LINQ
(from tblRoom in tblRooms.AsEnumerable()
join tblPMaster in tblMaster.AsEnumerable()
on tblRoom.Field<int>("tblroomid") equals tblPMaster.Field<int>("tblroomid")
where tblPMaster.Field<string>("pday") == Pday
select tblRoom.Field<string>("roomName")).Distinct();
如果我尝试运行它
foreach (var myReader in query)
{
}
我收到以下错误
Specified cast is not valid.
这些是以下变量中的值,希望这有助于捕获错误
tblPMaster.pday = Jun 28 2011 12:00AM
Parameter Pday = 28/11/2011
我不知道我哪里做错了。有人可以帮助获得正确的 LINQ 查询吗?
将此转换为日期而不是字符串
tblPMaster.Field<string>("pday")
@javadotnetcoder,谢谢你的澄清。我想我找到了解决方案...
试一试:
DataTable tblMaster = new DataTable();
DataColumn dc = new DataColumn("pday", Type.GetType("System.String"));
tblMaster.Columns.Add(dc);
tblMaster.Rows.Add(new Object[]{"Nov 28 2011 12:00AM"});
tblMaster.Rows.Add(new Object[]{"Apr 27 2013 11:10PM"});
tblMaster.Rows.Add(new Object[]{"Jul 18 2011 12:00AM"});
tblMaster.Rows.Add(new Object[]{"Mar 19 2012 10:01PM"});
DateTime PDay = new DateTime(2011,11,28);
//foreach(var row in tblMaster.AsEnumerable())
//{
// Console.WriteLine("{0}", Convert.ToDateTime(row[0]));
//}
var qry = tblMaster.AsEnumerable()
.Where(p=>Convert.ToDateTime(p.Field<string>("pday"))==PDay);
//qry.Dump();
以上代码已在 LinqPad 上测试。也适用 ;)
干杯,Maciej
我正在尝试根据 Sql 创建 Linq 查询,但无法使其正常工作。
SQL
"select distinct(roomName) as RoomName, tblroomid as RoomId
from TblMaster,tblrooms
where tblrooms.tblroomid = TblPresentationMaster.tblroomid
and convert(datetime, PDay, 101)='" + Pday + "'";
LINQ
(from tblRoom in tblRooms.AsEnumerable()
join tblPMaster in tblMaster.AsEnumerable()
on tblRoom.Field<int>("tblroomid") equals tblPMaster.Field<int>("tblroomid")
where tblPMaster.Field<string>("pday") == Pday
select tblRoom.Field<string>("roomName")).Distinct();
如果我尝试运行它
foreach (var myReader in query)
{
}
我收到以下错误
Specified cast is not valid.
这些是以下变量中的值,希望这有助于捕获错误
tblPMaster.pday = Jun 28 2011 12:00AM
Parameter Pday = 28/11/2011
我不知道我哪里做错了。有人可以帮助获得正确的 LINQ 查询吗?
将此转换为日期而不是字符串
tblPMaster.Field<string>("pday")
@javadotnetcoder,谢谢你的澄清。我想我找到了解决方案...
试一试:
DataTable tblMaster = new DataTable();
DataColumn dc = new DataColumn("pday", Type.GetType("System.String"));
tblMaster.Columns.Add(dc);
tblMaster.Rows.Add(new Object[]{"Nov 28 2011 12:00AM"});
tblMaster.Rows.Add(new Object[]{"Apr 27 2013 11:10PM"});
tblMaster.Rows.Add(new Object[]{"Jul 18 2011 12:00AM"});
tblMaster.Rows.Add(new Object[]{"Mar 19 2012 10:01PM"});
DateTime PDay = new DateTime(2011,11,28);
//foreach(var row in tblMaster.AsEnumerable())
//{
// Console.WriteLine("{0}", Convert.ToDateTime(row[0]));
//}
var qry = tblMaster.AsEnumerable()
.Where(p=>Convert.ToDateTime(p.Field<string>("pday"))==PDay);
//qry.Dump();
以上代码已在 LinqPad 上测试。也适用 ;)
干杯,Maciej