1

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

3
  • var Rad = _context.vwAssignedNotCompleted .FirstOrDefault(x => x.AssignedToLName == @ViewBag.LastName && x.AssignedToFName == @ViewBag.FirstName);
    – qpc4ever
    Jul 25, 2019 at 15:09
  • hi, try to cast your ViewBag value to string. x.AssignedToLName == (string)@ViewBag.LastName Jul 25, 2019 at 15:22
  • Thanks! I tried that but I still get the same error. "An expression tree may not contain a dynamic operation".
    – qpc4ever
    Jul 25, 2019 at 15:27

1 Answer 1

1

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);
3
  • Did you have any data in your viewbag? Because now I'm not getting an error from razor, but my variable is null even though the viewbag has the correct value while debugging with a break point.
    – qpc4ever
    Jul 25, 2019 at 16:01
  • Sorry, I was declaring my variable in the wrong scope. Your code is correct, and you're the man !!! I can't thank you enough as I will be implementing this throughout my application. Thank you, thank you!
    – qpc4ever
    Jul 25, 2019 at 16:17
  • I'm glad to help you! Jul 25, 2019 at 16:39

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.