2013-02-28 28 views
0

這是我的代碼。我想將這個列表保存在一個會話變量中以供稍後進行身份驗證(這是用戶有權訪問的對象列表....)我收到一個錯誤消息,說它不能將System.Collections.Generic.List隱式轉換爲「System」。 collections.Generic.List。幫幫我?將Linq查詢轉換爲列表時出錯

protected void Session_Start(object sender, EventArgs e) 
    { 
     string strUserName = User.Identity.Name; 
     string strShortUserName = strUserName.Replace("WINNTDOM\\", string.Empty).ToUpper(); 
     System.Web.HttpContext.Current.Session["strShortUserName"] = strShortUserName; 
     System.Web.HttpContext.Current.Session["strUserName"] = strUserName; 
     List<string> authorizedObjects = new List<string>(); 
     using (CPASEntities ctx = new CPASEntities()) 
     { 
      var w = (from t in ctx.tblUsers 
        where (t.UserPassword == strUserName) 
        select t).FirstOrDefault(); 
      if (!(w==null)) 
      { 
       authorizedObjects = (from t in ctx.qryUserObjectAuthorization 
             where (t.UserPassword == strUserName) 
             select new { n = t.ObjectName }).ToList(); 

      } 
     } 
    } 
+0

我刪除了不必要的「新」條款,和它的工作。感謝您的期待。 – 2013-02-28 17:20:33

回答

1

要生成的字符串列表使用

authorizedObjects = (from t in ctx.qryUserObjectAuthorization 
        where (t.UserPassword == strUserName) 
        select t.ObjectName).ToList(); 
1

authorizedObjectsList<string>但你想用它作爲匿名類型的列表:

List<string> authorizedObjects = new List<string>(); 

(...)

authorizedObjects = (from t in ctx.qryUserObjectAuthorization 
        where (t.UserPassword == strUserName) 
        select new { n = t.ObjectName, i = t.ObjectID }).ToList() 

更改查詢到:

authorizedObjects = (from t in ctx.qryUserObjectAuthorization 
        where (t.UserPassword == strUserName) 
        select t.ObjectName).ToList() 
+0

你也有答案,並且很好解釋。謝謝。 – 2013-02-28 17:58:12

1

您正在初始化一個List<string>對象,但填充了不同的對象。

List<string> authorizedObjects = new List<string>(); 

select new { n = t.ObjectName, i = t.ObjectID } <--construct a class with these properties and initialize `List<WithNewClassName>` 
+0

我從這個答案中學到了一些東西,謝謝。 – 2013-02-28 17:56:58