0

Environment: VS 2017 Entity Framework 6.0

    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new pubsEntities())
            {
                //this will throw an exception
                var employees = ctx.Database.SqlQuery<string>(@"
select * from employee;
                ").ToList();
            }
        }
    }

Receiving this error:

{"The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types."}

2
  • 1
    I suppose that you should get a List<string> not a single string Commented Mar 6, 2019 at 17:16
  • Either use EF or direct SQL, not both. Commented Mar 6, 2019 at 17:18

2 Answers 2

1

It will depend on your model (type property name, sql columns name,...).

If you want to use SqlQuery:

public class MyDTO {
    string p1 {get; set;}
    int p2 {get; set;}
    //...
}

var employees = ctx.Database.SqlQuery<MyDTO>(@"
    select someString as p1, someInt as p2 from employee").ToList();

Otherwise you probably have an employees table in your context:

var employees = ctx.Employees.ToList();

or

var employees = ctx.Employees.Where(x => x.Name == "Doe").ToList();

If you persist with string:

var employees = ctx.Database.SqlQuery<string>(
    @"select someString from employee;").ToList();
Sign up to request clarification or add additional context in comments.

Comments

1
select * from employee

Presuming that the employee table has multiple columns (id, name, dob etc), then your query will return multiple columns.

ctx.Database.SqlQuery<string>(...)

This will try and project those multiple columns into a string, which is not possible, hence your error message.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.