3

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?

3 Answers 3

3

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"]
                };
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Yes. like this :

var account = dbcontext.AccountDataModel.FromSql(@"select a.id, a.name from account a where a.id=123");

source : FromSql for non entity type

2 Comments

I dont want to use AccoutDataModel, I know i can map from sql to my POCO class (like I mentioned in the example) I want to retrieve a column example 'name' to var name = dbcontext.XXXX....
you mean something like that : learnentityframeworkcore.com/… ? (section Leveraging ADO.NET via the Context.Database property)
0

This queries the database

 var name = dbcontext.GetDBConnection().Query("select name from account where id=123").FirstOrDefault();

2 Comments

@Ben Updated answer
I am unable to get instance GetDbConnection() and if I use dbcontext.Database.GetDbConnection() then Query(..) not found. Do i need to install NuGet package?

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.