2015-04-26 112 views
0

我想,我理解它並且不會有問題。但現在我很困惑。我有以下代碼:'只支持原始類型,枚舉類型和實體類型'

public class ProjectMemberUserRolesElementViewModel 
{ 
    public string AccessType { get; set; } 
    public bool Delete { get; set; } 
    public bool Create { get; set; } 
    public bool Edit { get; set; } 
    public bool Read { get; set; } 
} 


var elements = from i in db.ProjectAccessTypes 
       select new ProjectMemberUserRolesElementViewModel() 
       { 
        AccessType = i.Type, 
        Create = (i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID) != null) ? (from p in i.ProjectMemberAccess where p.ProjectMemberID == ProjectMemberID select p.Create).FirstOrDefault() : false, 
        Delete = (i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID) != null) ? i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Delete).FirstOrDefault() : false, 
        Edit = (i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID) != null) ? i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Edit).FirstOrDefault() : false, 
        Read = (i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID) != null) ? i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Read).FirstOrDefault() : false 
       }; 

爲什麼我得到這個錯誤?這裏的原始類型不在哪裏?

+1

您可以替換'X? x:false' with'x ??假' – SLaks

+0

錯誤運算符'??'不能應用於類型'bool'和'bool'的操作數\t;) –

+1

將'p.Delete'轉換爲'bool?'。然而,'bool'的默認值是'false',所以你完全不需要這個。 – SLaks

回答

0

解決方法很簡單:

elements = from i in db.ProjectAccessTypes 
       select new ProjectMemberUserRolesElementViewModel() 
       { 
        AccessType = i.Type, 
        Create = i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Create).FirstOrDefault(), 
        Delete = i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Delete).FirstOrDefault(), 
        Edit = i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Edit).FirstOrDefault(), 
        Read = i.ProjectMemberAccess.Where(p => p.ProjectMemberID == ProjectMemberID).Select(p => p.Read).FirstOrDefault() 
       }; 
0

非原始類型是您的類型ProjectMemberUserRolesElementViewModel。我假設這種類型不是你的EF模型的一部分,但是你的視圖模型類的一部分。因此,在編譯爲SQL時,EF無法投影到此類型。

解決方案:改爲使用.AsEnumerable()方法轉到匿名類型,然後將項目轉到您的視圖模型類型。

+0

AsEnumerable()會打破子查詢。 – SLaks

+0

然後爲什麼代碼(從我db.ProjectAccessTypes 選擇新的ProjectMemberUserRolesElementViewModel() { AccessType = i.Type })。ToList();工作正常? –

相關問題