JimS-CLT
JimS-CLT

Reputation: 675

Error converting Linq query to list

Here's my code. I want to save the list in a session variable for later authentication (it's a list of objects the user is authorized to access....) I get an error saying it cannot implictly convert System.Collections.Generic.List to 'System.collections.Generic.List. Help?

    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();

            }
        }
    }

Upvotes: 0

Views: 233

Answers (3)

D Stanley
D Stanley

Reputation: 152644

To generate that as a list of strings use

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

Upvotes: 1

Sunny
Sunny

Reputation: 4809

You are initializing a List<string> object but populating different object.

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

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

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

authorizedObjects is List<string> but you're trying to use it as a List of anonymous type:

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()

Change your query to that:

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

Upvotes: 1

Related Questions