繁体   English   中英

在不使用数据集的情况下通过Sql存储过程在ASP.Net MVC模型中保存多个结果集

[英]Hold Multiple Result Set in ASP.Net MVC Model through Sql Stored Procedure Without Using DataSet

有作为过程有两个如下所示的Select语句:-

Create PROCEDURE sp_test
As
Begin  
   Select RegId,Name from tblRegistration
   Select UserId,UserName from tblUser

End

现在,我有两个表的模型

public class Registration
{
public Int64 RegId { get; set; }
public string Name  { get; set; }
}

public class User
    {
        public Int64 UserId { get; set; }
        public string UserName   { get; set; }
    }

我需要在下面的两个使用“公共类”的模型中填充数据,并且不想多次击中数据库

public class Common
    {
        public List<Registration> registration { get; set; }
        public List<User> user { get; set; }
    }

使用以下代码连接数据库

public T StoredProcedureMultipleResult(string spQuery, object[] parameters)
    {
        using (DbConfig dbContext = new DbConfig())
        {
            string param = "";
            for (int i = 0; i < parameters.Length; i++)
            {
                param = param + "{" + i.ToString() + "},";
            }

            int index = param.LastIndexOf(',');

            string sql = "[" + spQuery + "] " + param.Substring(0, index);

            T t = (T)dbContext.Database.SqlQuery<T>(sql, parameters).AsQueryable<T>();

        }
        var value = typeof(T);
        return (T)Convert.ChangeType(value, typeof(T));
    }

尊敬的Adnan,请使用Dataset进行相同操作。 如果不使用ADO.net中的数据集,则无法保留多个表。

尝试使用SqlDataReader ,它将一次从两个SELECT语句中检索所有数据-数据库上没有多次命中。 然后,根据需要多次使用NextResult() ,以将数据传输到您的Model对象中。

例如,一旦您将数据接收到SqlDataReader中(使用ExecuteReader()命令),就可以编写以下代码:

if (reader.HasRows)
{
    #region Result #1
    // (you can use reader.Read() to iterate through all rows of the result)
    while (reader.Read())
    {
        // Populate data from the first result into your model object
    }
    #endregion

    #region Result #2
    reader.NextResult();
    if (reader.HasRows)
    {
        // Populate data from the second result into your model object/s
        while (reader.Read())
        {
             // your statements come here
        }
    }
    #endregion
}

查看此链接以获取更多详细文档

暂无
暂无

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

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