2015-04-06 317 views
0

我想從後面的Sql創建Linq查詢,但無法讓它工作。從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) 
{ 
} 

我收到以下錯誤

指定的轉換無效。

這些都是在下面的變量值,希望這有助於在捕獲錯誤

tblPMaster.pday = Jun 28 2011 12:00AM 
Parameter Pday = 28/11/2011 

我不知道我做錯了。有人可以幫助獲得正確的LINQ查詢嗎?

+2

你有什麼具體的代碼問題? – Servy

+0

@Servy對不起,我錯過了錯誤的詳細信息,現在我已經添加了它。 – javadotnetcoder

+0

例外是告訴你,你的類型之一是錯誤的。 – Jason

回答

0

@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

+0

感謝@Macieji它的工作原理 – javadotnetcoder

+0

@javadotnetcoder,y你非常歡迎;) –

0

投這個至今沒有串

tblPMaster.Field<string>("pday") 
+0

你是不是指'tblPMaster.Field (「pday」)'? – abatishchev

+0

是的。我不知道,但如果它的工作。即時消息不在我的電腦atm。但請嘗試一下。 :) –

+0

另外。你的問題有兩種情況。它要麼是你正在施放的投射或是數據。例如(將一個雙精度數據轉換爲一個日期時間)拋出的錯誤拋出無效 –