问题描述
我在数据库中有几列视图.我正在尝试这个查询
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();
我注意到问题出在TestEntity上,因为当我使用字符串而不是TestEntity时,它起作用了.有什么建议我在这里做错了吗?
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?
推荐答案
只需替换下面的代码
var res = dbContext.Database.SqlQuery<TestEntity>("Select * from dbo.MyView").ToList();
与此并重试...
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
和您的
用于相同的列.因为如果MyView和TestEntity中有不同的列,那么它将无法工作...
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...
谢谢...
这篇关于如何从非实体类型的SQL查询中检索多个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!