问题
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