Linq filter with instructions stored in a session

I am using this code to filter Linq data and it keeps crashing.

public ActionResult Index()
{

    var model = db.Tickets
            .Include(t => t.TicketNotes)
            .Where(t => t.OpenUserId == Guid.Parse(Session["LogedUserID"] as string))
            .OrderBy(t => t.OpenDate)
            .ToList();

    return View(model);
}

      

The error I am getting:

An exception of type "System.NotSupportedException" occurred in EntityFramework.SqlServer.dll but was not handled in user code

The error I know is on this line:

.Where(t => t.OpenUserId == Guid.Parse(Session["LogedUserID"] as string))

      

because it worked when the Guid was hardcoded like in this case:

public ActionResult Index()
{

    var model = db.Tickets
                  .Include(t=>t.TicketNotes)
                  .Where(t.OpenUserId == new Guid("00000000-0000-0000-0000-000000000000"))
                  .OrderBy(t=>t.OpenDate);

    return View(model);
}

      

+3


source to share


2 answers


You are getting this error because Linq code is being converted to SQL. There is Guid.Parse

no method in SQL .

In your example with, Where(t.OpenUserId == new Guid("00000000-0000-0000-0000-000000000000"))

you don't parse anything (call any method), you just create a new Guid

one that is supported.

The fashion will be Parse

Guid

out Where

.



var userId = Guid.Parse(Session["LogedUserID"] as string); // conversion is done outside Where
var model = db.Tickets
        .Include(t => t.TicketNotes)
        .Where(t => t.OpenUserId == userId)
        .OrderBy(t => t.OpenDate)
        .ToList();

      

Another easy way to fix this is by adding ToList()

. As @entropic mentioned this will enumerate through the whole table and is not recommended for large tables.

var model = db.Tickets
        .Include(t => t.TicketNotes)
        .ToList() // < added here
        .Where(t => t.OpenUserId == Guid.Parse(Session["LogedUserID"] as string))
        .OrderBy(t => t.OpenDate)
        .ToList();

      

+4


source


Please try this, should work



Guid g = Guid.Parse(Session["LogedUserID"] as string);

var model = db.Tickets
                .Include(t => t.TicketNotes)
                .Where(t => t.OpenUserId == g)
                .OrderBy(t => t.OpenDate)
                .ToList();

      

+4


source







All Articles