2009-09-22 33 views
0

我有問題映射。我讀「數據整形功能」 scottGU後 - http://weblogs.asp.net/scottgu/archive/2007/06/29/linq-to-sql-part-3-querying-our-database.aspxlinq2sql:在查詢中顯式構造實體類型'#some type#'是不允許的 - 同樣使用連接

但我已經試過這種

 IQueryable<AccessRights> accessRights = 
          from t1 in this.db.AccessRights 
          join t2 in this.db.AccessRightsExtra 
          on t1.IdAccessRights equals t2.IdAccessRights 
          where t2.IdUser== userId 
          select new AccessRights 
          { 
           IdAccessRights = t1.IdAccessRights, 
           Description= t2.Description 
          }; 

,但產生在查詢這個錯誤「實體類型的‘#some類型#’顯式建築是不允許的「

按照鏈路scottgus後上述,我也嘗試過(通知後在選擇新的缺失型)

 IQueryable<AccessRights> accessRights = 
          from t1 in this.db.AccessRights 
          join t2 in this.db.AccessRightsExtra 
          on t1.IdAccessRights equals t2.IdAccessRights 
          where t2.IdUser== userId 
          select new 
          { 
           IdAccessRights = t1.IdAccessRights, 
           Description= t2.Description 
          }; 

但這機生產線ces

不能將類型'System.Linq.IQueryable'隱式轉換爲'System.Linq.IQueryable'。存在明確的轉換(您是否缺少演員?)

真的很感謝任何人都有的見解。

回答

4

如何:

IEnumerable<AccessRights> accessRights = 
    // This bit works in the database 
    (from t1 in this.db.AccessRights 
    join t2 in this.db.AccessRightsExtra 
    on t1.IdAccessRights equals t2.IdAccessRights 
    where t2.IdUser== userId 
    select new 
    { 
     IdAccessRights = t1.IdAccessRights, 
     Description= t2.Description 
    }) 
    .AsEnumerable() // From here on it's in-process 
    .Select(x => new AccessRights 
      { 
       IdAccessRights = x.IdAccessRights, 
       Description= x.Description 
      }); 

注意,結果是IEnumerable<T>而非IQueryable<T>,但它仍然會懶洋洋地評估。這會導致問題嗎?

另外,使用隱式類型的局部變量只使用匿名類型:

var accessRights = from t1 in this.db.AccessRights 
        join t2 in this.db.AccessRightsExtra 
        on t1.IdAccessRights equals t2.IdAccessRights 
        where t2.IdUser== userId 
        select new 
        { 
         IdAccessRights = t1.IdAccessRights, 
         Description= t2.Description 
        }; 

這仍然將是一個IQueryable<T>但如果T是一個匿名類型。你將不能夠以此爲IQueryable<AccessRights>但如果所有你需要的是IdAccessRightsDescription屬性,你只需要他們在同樣的方法,這可能是對你不夠好......

+0

謝謝喬恩! ..是的第二個工作,問題是我需要把它投給IQueryable 所以我嘗試了以下,但測試爲空。 IQueryable test = accessRights as IQueryable ; 是否有一種特殊的方式將它轉換爲我的IQueryable ?匿名類型的列名與AccessRights完全相同? – 2009-09-22 11:04:01

0

這是可能的如果你創建一個新的派生類,而不[表] -Attribute這樣的:

public class AccessRightsLocal : AccessRights 
{ 
} 

然後您可以創建「AccessRightsLocal」內選擇的一個實例。將新實例投射到「AccessRights」,它將起作用!

IQueryable<AccessRights> accessRights = 
        from t1 in this.db.AccessRights 
        join t2 in this.db.AccessRightsExtra 
        on t1.IdAccessRights equals t2.IdAccessRights 
        where t2.IdUser== userId 
        select (AccessRights) new AccessRightsLocal 
        { 
         IdAccessRights = t1.IdAccessRights, 
         Description= t2.Description 
        }; 
相關問題