1

I'm trying to execute a query against multiple columns in EF 6 (using C# WPF on VS 2013), I need to select all fields of some columns. I really don't know much but I already tried to do it with Linq and it doesn't seem to have that functionality, so I went with <context>.Database.SqlQuery<string>(query), but it's unclear to me how should I handle what it returns. The query is something simple like "SELECT column1,column2 FROM table".

Is it possible to do it with Linq? How? And for the SqlQuery() case, How should I handle it's result, being most of its columns are in string format?

7
  • 1
    Yes, it's possible using linq: context.Table.Select(x => new { x.Column1, x.Column2 });. Feb 16, 2014 at 17:23
  • Hey! MarcinJuraszek, thanks for the quick answer. How do I handle it? I put ToArray() but I guess it should be an IEnumerable or something, but it says AnonymousType#1 Feb 16, 2014 at 17:40
  • @MiloGP What you have done so far ?? Can you post some code ?? Feb 16, 2014 at 18:23
  • I made this, I'm not so sure but something like that worked before for me. string[] lista = (db.tbl_pacientes.Select(x => new { x.pac_pk_id, x.pac_nombre1 })).ToArray(); Feb 16, 2014 at 18:38
  • @MiloGP Post an answer if you found something that worked for you. Feb 17, 2014 at 2:13

1 Answer 1

3

@MiloGP yes you can do it with using Lambda Expression with LINQ

Here a example:

I have 5 columns in table employee(emp_id,emp_name,emp_dob,emp_address,emp_reference)

and My DBContext name : EmployeeEntities;

I trying to get emp_name and emp_address

List<employee> = EmployeeEntities.employees.select( x => new { x.emp_name, x.emp_address }).ToList();

if you need to get value of someone, As a example emp_id == 13458

List<employee> = EmployeeEntities.employees.Select( x => new { x.emp_name, x.emp_address }).Where( y => y.emp_id == 13458).ToList();

2
  • Thanks! That's the way. But what I was actually trying to do was getting all values without the need to specify all the field names, as there's a lot of fields in some of the tables on the project. But I guess that's not possible. Is it? Apr 20, 2014 at 14:41
  • No it is possible.. To get all of the fields you have to change the code to following. List<employee> = EmployeeEntities.employees.ToList(); It will get all the employees. if need to get someone details then use following. List<employee> = EmployeeEntities.employees.Where(x=>x.emp_id == 13458).ToList(); Apr 21, 2014 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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