qpc4ever
qpc4ever

Reputation: 67

Unable to use ViewBag or any other dynamic variable inside linq statement

I simply want to get back the data where the AssignedToLName is equal to the currently signed-in user. I am using windows authentication, and I have a base controller where I am setting the logged in Windows user first name and last name in view bags. I use them all over the place, so I know the view bags are not the issue. But linq won't let me use a view bag in my statement. I tried to put the viewbag in a variable, and then use the variable in the statement but that failed as well.

"An expression tree may not contain a dynamic operation" is my error.

I've seen some similar questions, but none with current syntax. Is there a workaround to use a viewbag inside a linq statement? Or even just a workaround to use my current logged in Windows user in the linq statement?

    //my linq statement
    var Rad = _context.vwAssignedNotCompleted
    .FirstOrDefault(x => x.AssignedToLName == 
    @ViewBag.LastName && x.AssignedToFName == 
    @AssignedToFName);

   //My ViewBags
    UserPrincipal user = UserPrincipal.Current;

    var groups = user.GetAuthorizationGroups();
    ViewBag.LastLogon = user.LastLogon;
    ViewBag.DisplayName = user.DisplayName;
    ViewBag.FirstName = user.GivenName;
    ViewBag.LastName = user.Surname;
    ViewBag.WSIP = user.Description;

The expected result is that I get back the database data for the current logged in Windows user

Upvotes: 1

Views: 193

Answers (1)

Vladimir Bolshakov
Vladimir Bolshakov

Reputation: 410

I wrote a simple test, and my code works fine in a razor:

var name = (string)ViewBag.Name ?? "";
var profile = context.Profiles.FirstOrDefault(x => x.Name == name);

Upvotes: 1

Related Questions