How to get only two fields from the table by linq query?

Viewed 65

I have a .net core(v 3.1) in which i have installed Microsoft SQL Server database provider nuget package for Entity Framework Core.

I want to get only two feilds from the database?

Error : Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'System.Linq.IQueryable<<anonymous type: string Name, string Number>>' to 'ExampleAuth.Model.Employee'. An explicit conversion exists (are you missing a cast?)

public Employee GetById(int id)
    {
        var response = db.Employee.Where(x => x.Id == id).Select(x => new{x.Name,x.Number});
        return response;
    }

API Is...

    [HttpGet]
    [Route("GetById/{id}")]
    public Employee GetById(int id)
    {
        if (id != 0)
        {
            return bl.GetById(id);
        }
        else
        {
            throw new Exception("! No Data Found");
        }
    }
3 Answers

A couple of things. Firstly, you are trying to return the entire query rather than a single employee. Secondly, you are creating an anonymous type rather than an instance of the Employee class. Your code should look something like this:

var response = db.Employee
    .Single(x => x.Id == id) // Use single to get an individual item
    .Select(x => new Employee // Make a new Employee object
    {
        Name = x.Name,
        Number = x.Number
    });

Now response contains a single Employee object. Note this will throw an exception if there is no matching employee with that ID, but that is likely a good idea. You could handle that by replacing Single with SingleOrDefault.

I got the solution... it is look like..

public Employee GetById(int id)
    {
        var response = db.Employee
            .Where(x => x.Id == id)
            .Select(x => new Employee{Name = x.Name,Number = x.Number}).FirstOrDefault();
        return response;
    }

Thanks to all...

Try this below query

var response = (from objEmp in db.Employee where objEmp.Id == id select new
    {
        Name = objEmp.Name,
        Number = objEmp.Number
    }).FirstOrDefault();

if(response  != null)
{
response.Name // For access name
response.Number // For access number
}
Related