0

I am working on Database First Approach in Entity Framework where I have to retrieve specific columns from the Entity.

Public IQueryable<Entity.Employees> GetEmployeeName(String FName,String LName)
{
     var query = (from s in Employees
                  where s.firstName = FName && s.lastName = LName
                  select new {s.firstName, s.middleName});
     return query;
}

Here return statement is throwing an error where it seems that its not matching with Employees (entity) columns. Could you please help me in sorting out this issue? Thanks in advance.

user3129206
  • 117
  • 1
  • 7

1 Answers1

0

You need to use == for comparison, also you need to use dynamic type as return type since you are returning a custom anonymous type. Try this

Public IQueryable<dynamic> GetEmployeeName(String FName,String LName)
{
var query=(from s in Employees
where s.firstName==FName && s.lastName==LName
select new {s.firstName,s.middleName});
return query.AsQueryable();
}

Finally you will use it like below, keep in mind that intelisense won't work on dynamic object.

var query = GetEmployeeName("Jake", "Smith");
            List<dynamic> results = query.ToList();
            foreach (dynamic result in results)
            {
                string fristName = result.FirstName;
                string lastName = result.MiddleName;
            }
Mazhar Qayyum
  • 630
  • 7
  • 22
  • I have modified to == but the issue i am facing is in Entity.Employees we have 4 columns but the var query i want only 2 columns in the select statement. So I am getting the error as below: 'Anonymous Types: a is new {} Cannot implicitly convert type 'System.Linq.IQueryable'<>' to'System.Linq.IQueryable'.An explicit conversion exists(are you missing a cast?)' – user3129206 Nov 23 '16 at 07:58
  • I just updated my post. Since you are returning anonymous type you need to use dynamic type as return type. Alternatively you can create a custom wrapper type with two fields FirstName and MiddleName and return that instead. This will allow you to have intelisense working when get data back from result. – Mazhar Qayyum Nov 23 '16 at 08:29
  • I am trying to access this method method [link](http://localhost:1985/Employee.svc/GetEmployeeName?FName='Jake'&LName='Smith') but getting error. I want to get the specific columns instead of entire entity columns.Could you please suggest or provide a sample snippet how to achieve this.Thanks in Advance. – user3129206 Nov 26 '16 at 17:24