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

有些话、适合烂在心里 提交于 2019-12-12 13:12:23

问题


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?


回答1:


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...



来源:https://stackoverflow.com/questions/37413787/how-to-retrieve-multiple-columns-from-non-entity-type-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!