Home > Blockchain >  I am using MVC and trying to pass value to my view from Query
I am using MVC and trying to pass value to my view from Query

Time:11-14

I am trying to pull the fullname from my context as follows:

string fullname = context.Employees.Where(e => e.EmployeeId == employeeId).Select(f => f.FullName).ToString();

In my view instead of the fullname I get:

Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String]

Putting breakpoints in the code, I see the assignment to the string fullname, does not show the name but the Microsoft.Entity message.

CodePudding user response:

That's because the result is maybe null or maybe more than one result,

if you want to control null returns while using EF Core, it's better to use FirstOrDefault() method.

In this case, it returns only one result or null.

string fullname = context.Employees.Where(e => e.EmployeeId == employeeId).FirstOrDefault().Select(f => f.FullName).ToString();

CodePudding user response:

string fullname = context.Employees.Where(e => e.EmployeeId == employeeId)
        .Select(f => f.FullName)
        .FirstOrDefault();

Use FirstOrDefault() to get the first element of a sequence. You should check fullname == null in case a sequence contains no elements.

CodePudding user response:

This code:

context.Employees.Where(e => e.EmployeeId == employeeId).Select(f => f.FullName).ToString();

produces "Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.String]"

... as a result because you are using ToString() to get the string value of the IQueryable Linq Expression. It does not execute your query.

If you expect one employee to come back and want that employee's FullName:

context.Employees
    .Where(e => e.EmployeeId == employeeId)
    .Select(f => f.FullName)
    .Single();

This tells EF to execute the expression to return just the FullName of a matching employee. Since FullName is expected to be a string there is no need to append a ToString() on top of that after the Single(). If "employeeId" might not actually match an Employee record you can use .SingleOrDefault() and handle that you might get back #null for the Employee name.

The use of FirstOrDefault() should be avoided unless you expect that there can be multiple matches and you only want the first one. It should always be used with an OrderBy / OrderByDescending clause to ensure a predictable result is returned each time. Using SingleOrDefault will throw an exception if there are two or more records, Single with throw if anything other than one records exists. This provides a guard in your logic that detects when something in your code or data state is making a bad assumption and should be addressed. FirstOrDefault will "hide" these bad assumptions, usually to be noticed far too late when there is considerable "bad data" in the system to address.

  • Related