2010-11-03 51 views
1

我想連接兩個表,但兩個連接字段的格式不同: 一個是小數,一個是字符串。Linq to entities/EF:連接到小數點和字符串字段的表

當我做小數的ToString()或字符串的Convert.ToDecimal()時,Linq不接受這個。

有沒有辦法實現我想要的?

var tmp = from c in gge.GiftCards 
    join p in gge.Customers 
on c.OwnerId equals p.customer_Key 
    into g 
    from o in g.DefaultIfEmpty() 
    select new MyCardViewModel {GiftCard = c, Customers= g}; 
+0

可能在ESQL中,但是...我會修改數據庫。 – 2010-11-03 20:26:54

+0

haha​​ha,謝謝:)這有點奇怪,因爲字符串字段可以指向其他字段,在這種情況下它是一個小數字段。 – Michel 2010-11-04 22:47:30

回答

1

我會非常傾向於修復數據庫。你不要在你的問題中說哪個字段是字符串,哪個是小數,但是不管怎樣,我不認爲使用小數作爲關鍵字是有意義的。如果它們都是字符串,整數或GUID,會更好。儘管如此,你還有其他選擇。

第一個選項是添加一個視圖或一個存儲過程,在字段到達EF之前轉換其中一個字段。

另一種選擇是將較小的一組數據存入內存並通過代碼強制轉換。如果我認爲GiftCards越小集和OwnerId是小數,那麼你可以試試這個:

var gcs = gge.GiftCards 
    .Select(gc => gc.OwnerId) 
    .ToDictionary(x => x.OwnerId.ToString(), x => x); 

var gcIds = gcs.Keys.ToArray(); 

var results = (
    from p in gge.Customers 
    where gcIds.Contains(p.customer_Key) 
    select p) 
    .ToArray() 
    .GroupBy(p => p.customer_Key) 
    .Select(p => new MyCardViewModel 
     { 
      GiftCard = gcs[p.Key], 
      Customers = p.ToArray(), 
     }); 

做這些查詢會導致查詢,如要執行以下操作:

SELECT ... 
FROM [GiftCards] AS t0 

SELECT ... 
FROM [Customers] AS t0 
WHERE t0.[customer_Key] IN ("1", "2", "3", ..., "1442") 

設我知道這是否適合你。乾杯。

+0

非常好,這真的幫助我! – Michel 2010-11-05 22:34:07