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");
You cannot use context.Database.SqlQuery
with an anonymous type. You need to define you Student class (with Id, Name) and use it.
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(); } } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.