Executing Raw sql with Entity Framework Core

asp.net-core entity-framework entity-framework-core

Question

The below I can have a condition to execute view/table, which would load into AccountDataModel class.

 dbcontext.AccountDataModel.FromSql($"select * from account where id=123").FirstOrDefault();

How can I retrieve without using a class model, if I want to retrieve just 1 or 2 columns

example: select name from account where id=123

Do I always need a class model?

1
1
12/9/2019 8:47:34 PM

Popular Answer

ADO.NET works in EFCore =)

using Microsoft.EntityFrameworkCore;
using System.Data.Common;
using System.Data.SqlClient;
using System;

    public void ExampleMethod(DbContext context)
    {
        SomeObjectResult result = null;
        DbCommand cmd = context.Database.GetDbConnection().CreateCommand();
        cmd.CommandText = "Select C.ID, C.CarModelID as ModelID, C.VIN, C.RegNumber,cast(C.CountValue as int) as Course,A.BrandID from   A inner join C on A.ID = C.KeyID  Where A.ID = @appID";
        cmd.Parameters.Add(new SqlParameter("@appID", appointmentID));
        if (cmd.Connection.State != ConnectionState.Open)
        {
            cmd.Connection.Open();
        }
        using (var reader = await cmd.ExecuteReaderAsync())
        {
            if (reader.Read())
            {
                result = new SomeObjectResult()
                {
                    BrandID = (int)reader["BrandID"],
                    Course = (int)reader["Course"],
                    ID = (int)reader["ID"],
                    ModelID = (int?)reader["ModelID"],
                    RegNumber = (string)reader["RegNumber"],
                    VIN = (string)reader["VIN"]
                };
            }
        }
    }
1
12/9/2019 10:30:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow