1

How can I get output like first query from second query.

Query 1:

var students = context.Students.Select(o => new
        {
            id = o.StdId,
            name = o.Name
        });

Query 2:

var students = context.Database.SqlQuery<object/??>("SELECT  StdId id, Name name FROM Students");
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56

2 Answers2

0

You cannot use context.Database.SqlQuery with an anonymous type. You need to define you Student class (with Id, Name) and use it.

Igor Kulman
  • 16,211
  • 10
  • 57
  • 118
0

See code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = "Enter your connection string here";
            string SQL = "SELECT  StdId id, Name name FROM Students";

            SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);

            DataTable dt = new DataTable();
            adapter.Fill(dt);

            var student = dt.AsEnumerable()
                .Select(x => new { id = x.Field<int>("id"), name = x.Field<string>("name") }).ToList();

        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20