简体   繁体   English

C#ASP.NET MVC 5如何执行原始查询?

[英]C# ASP.NET MVC 5 How to execute a raw query?

I am trying to execute a raw query using c#. 我正在尝试使用C#执行原始查询。

Here is what I have done 这是我所做的

var accounts = conn.Database.SqlQuery<IEnumerable<string>>("SELECT TOP 1 a.* FROM zipcodes_to_accounts AS c " +
"INNER JOIN accounts AS a ON a.id = c.account_id " +
"WHERE c.zip_code = @p0 "+
"ORDER BY a.completed_ll + a.completed_cp ASC", zipcode).ToArray();

Then I want to take the first record and convert it to json object. 然后,我想获取第一条记录并将其转换为json对象。

if (accounts.Count() > 0)
{
    return JsonConvert.SerializeObject( accounts.First() ); 
}

But the query is giving me an error 但是查询给我一个错误

The result type 'System.Collections.Generic.IEnumerable`1[System.String]' may not be abstract and must include a default constructor. 结果类型'System.Collections.Generic.IEnumerable`1 [System.String]'可能不是抽象的,必须包含默认构造函数。

The accounts table has some columns that are varchar, datetime, integers. 帐户表具有一些列,这些列是varchar,datetime,integer。 How can I get this query to work? 我怎样才能使该查询工作?

UPDATED Converting the IEnumerable to list like advised in the answer it working. 更新IEnumerable转换为列表,如工作答案中所建议的那样。 but now the JsonConvert is returning an empty object. 但是现在JsonConvert返回一个空对象。 Here is my current code 这是我当前的代码

       //getAccount
        public string GetAccount()
        {


            string zipcode = StringHelpers.StringOrNull(Request["zip_code"]);

            if (zipcode != null)
            {

                var accounts = conn.Database.SqlQuery<List<string>>("SELECT TOP 1 a.* FROM zipcodes_to_accounts AS c " +
"INNER JOIN accounts AS a ON a.id = c.account_id "+
"WHERE c.zip_code = @p0 "+
"ORDER BY a.completed_ll + a.completed_cp ASC", zipcode).ToList();
                var firstAccount = accounts.FirstOrDefault();

                if (firstAccount != null)
                {
                    return JsonConvert.SerializeObject(firstAccount);
                }

            }

            return "{}";

        }

When I debug my code Here is what I see 当我调试代码时,这是我看到的

在此处输入图片说明

Not sure what ORM you're using, but the warning is telling you that IEnumerable cannot be constructed as it's an interface. 不确定您使用的是哪种ORM,但警告告诉您IEnumerable无法构建,因为它是一个接口。 Therefore the SqlQuery method can't know what return type you're expecting. 因此, SqlQuery方法无法知道您期望的返回类型。

Try replacing the generic constraint with a concrete type: 尝试用具体类型替换通用约束:

var accounts = conn.Database.SqlQuery<string>("SELECT TOP 1 a.* FROM zipcodes_to_accounts AS c " +
"INNER JOIN accounts AS a ON a.id = c.account_id " +
"WHERE c.zip_code = @p0 "+
"ORDER BY a.completed_ll + a.completed_cp ASC", zipcode).ToArray();

You're asking for a IEnumerable<string> which is an interface. 您需要一个IEnumerable<string> ,它是一个接口。 You need to pick a class that implements IEnumerable such as a List 您需要选择一个实现IEnumerable的类,例如List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM