2011-01-31 148 views
0

我想從實體數據上下文中使用linq加載自定義對象。這裏是我的代碼Ef CTP5:Linq查詢幫助

from category in _db.GetQueryable<DataModels.Category>() 
select new Category 
{ 
    Id = category.Id, 
    Name = category.Name, 
    CreatedBy = category.CreatedBy.HasValue ? new Login { Id = category.CreatedBy ?? Guid.Empty } : null 
} 

//Note: GetQueryable<DataModels.Category> actually use Set<DataModels.Category>() in DataContext class. 

但它產生以下錯誤:

Unable to create a constant value of type 'CodeOnly.EF.DomainModels.Login'. Only primitive types ('such as Int32, String, and Guid') are supported in this context. 

但上面的代碼,如果我使用LINQ2SQL總是工作。

任何想法如何在EF5代碼的情況下實現這一點。

+0

這裏只是一個瘋狂的猜測,但如果您將`CreatedBy`表達式移動到單獨的`let`子句中,您會得到同樣的錯誤嗎?這樣你就可以將其移出投影。 – 2011-01-31 04:18:54

+0

CreatedBy這裏是類別datamodel(可空的GUID)的屬性。所以不知道「let」在這裏很有用 – learner 2011-01-31 04:26:40

回答

0

在開始將其投影到自定義類型之前,您可能只需要將Category數據從數據庫中取出即可。

只得到你需要的,然後在你的集合上調用ToList()來執行並從數據庫中取出。然後你可以自由投射到你想要的任何類型。

var items = _db.GetQueryable<DataModels.Category>().ToList(); 
from category in items 
select new Category 
{  
    Id = category.Id, 
    Name = category.Name, 
    CreatedBy = category.CreatedBy.HasValue 
     ? new Login { Id = category.CreatedBy ?? Guid.Empty } : null 
} 

編輯:作爲新的信息明朗化,新的想法涌現出 - 試試這個:

partial class Category 
{ 
    public Category(int id, string name, Guid? createdByGuid) 
    { 
     Id = id; 
     Name = name; 
     CreatedBy = createdByGuid.HasValue ? new Login { Id = createdByGuid.Value } : null; 
    } 
} 

var items = _db.GetQueryable<DataModels.Category>().ToList(); 
from category in items 
select new Category(category.Id, category.Name, category.CreatedBy) 

我也想知道爲什麼在你原來的問題,你正在檢查的GUID? 兩次爲空(HasValue??) - 但我不認爲這是什麼導致你的問題。