如何从SQL查询返回的动态对象 [英] How to return dynamic object from SQL query

查看:434
本文介绍了如何从SQL查询返回的动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有情况,即storeprocdure回报集合,但我也不怎么对象的结构,因为查询是非常动态的。

I have situation where a storeprocdure return collection, but I do not how the object structure because the query is very dynamic.

一个查询可以返回:

ID |位置| MarketSegment | ... n列

Id | Location | MarketSegment | ... n columns

和另一个可以返回

ID |销售代表|位置|地区| ... n列

Id | Sales Rep | Location | Region | ... n columns

我只是简单地返回一个对象,因为你可以在下面的code看到的。我知道这是行不通的,但我怎么能设定,让它呢?

I am simply just return a "object" as you can see in the code below. I know this won't work, but how can I set it up so it does?

using (DbContext db = new Context())
{

    var items = db.Database.SqlQuery<object>(
        "SP @Param1, @Param2",
        new SqlParameter("Param1", ped),
        new SqlParameter("Param2", 25)
    ).ToList();

    return Request.CreateResponse<List<object>>(HttpStatusCode.OK, items);
}

编辑:

我不知道,如果显示的SP将在帮助不管怎么说,但如果我能更多的解释。

I don't know if showing the SP will help in anyways, except if I can explain it more.

每个列重新psented作为自定义字段$ P $。用户可以创建自定义字段的n个号码。所以,如果你运行用户1 SP和他有5个自定义字段中的列psented那么每个自定义字段将被重新$ P $,但如果用户2有3个自定义字段中,只有3列将被重新presented。我不拥有控制权的是自定义字段名称和自定义字段的数量。

Each columns are represented as Custom Fields. Users are able to create n numbers of Custom Fields. So If you run the SP for User1 and he has 5 custom fields, then each custom fields will be represented in Columns, but If User2 has 3 custom fields, only 3 columns will be represented. What I don't have control over is the Custom Field Name and number of custom fields.

推荐答案

您不能使用的 类SqlQuery&LT; T&GT; 自定义字段

You can't use SqlQuery<T> for custom fields.

创建一个原始SQL查询,将返回给定的通用元素
  类型。类型可以是任何类型的具有匹配的性能
  列
的名称从查询返回的,也可以是一个简单的
  基本类型。 - MSDN

Creates a raw SQL query that will return elements of the given generic type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. - MSDN

但是,你可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader%28v=vs.110%29.aspx\"相对=nofollow> 的ExecuteReader 来实现这一目标。

But, you can use ExecuteReader to achieve that.

using (var db = new Context())
{
    db.Database.Connection.Open();

    var cmd = db.Database.Connection.CreateCommand();
    cmd.CommandText = "SP @Param1, @Param2";
    cmd.Parameters.Add(new SqlParameter("Param1", ped));
    cmd.Parameters.Add(new SqlParameter("Param2", 25));

    List<List<object>> items = new List<List<object>>();
    var reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        var item = new List<Object>();
        items.Add(item);

        for (int i = 0; i < reader.FieldCount ; i++)
            item.Add(reader[i]);
    }

    return Request.CreateResponse<List<object>>(HttpStatusCode.OK, items);
}

这篇关于如何从SQL查询返回的动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆