2

我有一個IQueryable到字符串[]轉換的問題。當我將IQueryable轉換爲字符串時,我得到了一個N​​otSupportedException []

public string[] GetRolesForUser(User user) 
    { 
     if (!UserExists(user)) 
      throw new ArgumentException(MissingUser); 

     var qry = from x in entities.Roles 
       where x.Users.Contains(user) 
       select x.RoleName; 

     return qry.ToArray(); // At this point I've got a NotSupportedException 
    } 

異常消息:

無法創建類型的恆定值 'SchoolMS.Models.Entities.User'。在此上下文中僅支持基本類型(如Int32,String和Guid)。

請幫忙,我該如何解決這個問題?什麼是正確的方法?

(我使用的是EF 4.1 MVC3)

+0

我猜這個問題是在'x.Users.Contains()'。 'x.Users ==用戶'會工作嗎? – 2012-02-11 10:26:13

+0

我試過了,但我有同樣的例外 – mrtn 2012-02-11 10:35:52

回答

0

問題解決。

我使用的是許多人我的用戶和角色之間的多對多關係(UsersInRoles表提供的話),這就是爲什麼我的查詢是不適合這種

我改變了我的方法內的查詢和它的工作很好..

public string[] GetRolesForUser(User user) 
{ 
    if (!UserExists(user)) 
     throw new ArgumentException(MissingUser); 

    var qry = entities.Users 
     .Where(u => u.UserID == user.UserID) 
     .SelectMany(x => x.Roles.Select(r => r.RoleName)); 

    return qry.ToArray(); 
} 
1

我懷疑的問題是,實體框架不能在查詢中user變量創建一個常量。一個解決方案是創建一個手動加入,而不是使用Contains

var qry = from x in entities.Roles 
      join Users u on u.RoleId = x.Id 
      where u.Id = user.Id 
      select x.RoleName 
0

我會考慮寫

var qry = from x in entities.Roles 
    where x.Users.Select(u => u.Id).Contains(user.Id) 
    select x.RoleName; 

因此,這將是一個原始類型,如要求。

相關問題