Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve multiple columns from non-entity type sql query?

I have a view in database with several columns. I am trying this query

public class TestEntity
{
    public string ref { get; set; }
    public string Name { get; set; }
    public string Batch { get; set; }
}
var res = dbContext.Database.SqlQuery<TestEntity>("Select * from dbo.MyView").ToList();

but this returns list of objects with only null values and no data. However, when I try to retrieve single column like this it works

var res = dbContext.Database.SqlQuery<string>("Select Name from dbo.MyView").ToList();

I have noticed that the problem is with the TestEntity because when I use string instead of TestEntity it works. Any suggestion what am I doing wrong here?

like image 273
fredzyadi Avatar asked Apr 29 '26 01:04

fredzyadi


1 Answers

just replace the below code

var res = dbContext.Database.SqlQuery<TestEntity>("Select * from dbo.MyView").ToList();

with this and try again...

var res = dbContext.Database.SqlQuery("Select * from dbo.MyView").ToList<TestEntity>();

and if still that is not working then you need to check for your

TestEntity

and your

dbo.MyView

for same columns. because if there is different columns in MyView and TestEntity then it will not work...

If you change the column name in query, then it will throw an exception or it'll not work properly...

if this'll help you then don't forget to mark...

Thanks...

like image 147
Mayur Siddhapura Avatar answered May 01 '26 14:05

Mayur Siddhapura