Stored procedures EF and NET CORE

不羁的心 提交于 2020-01-22 12:57:32

问题


I am building a WEB API to generate JSON objects in .net core

The thing is the data sets are generated in SQL stored procedures (using dynamic SQL) and i dont know the type of objects that are returned so i can map it to a concrete model, since the output columns change depending on the parameters.

Does any one know ho to retrive the data set from the BD in net core 1.0 with or without using EF?

Browsed a lot and can only find ansers that use models

Thanks in advance


回答1:


You can add the following dependencies for your project in project.json file:

  • System.Data.Common
  • System.Data.SqlClient

As you can see in the next image:

Rebuild your project and you can code something like this:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Dynamic;

namespace ConsoleApp1
{
    public class Program
    {
        public static IEnumerable<dynamic> GetData(String cmdText)
        {
            using (var connection = new SqlConnection("server=(local);database=Northwind;integrated security=yes;"))
            {
                connection.Open();

                using (var command = new SqlCommand(cmdText, connection))
                {
                    using (var dataReader = command.ExecuteReader())
                    {
                        var fields = new List<String>();

                        for (var i = 0; i < dataReader.FieldCount; i++)
                        {
                            fields.Add(dataReader.GetName(i));
                        }

                        while (dataReader.Read())
                        {
                            var item = new ExpandoObject() as IDictionary<String, Object>;

                            for (var i = 0; i < fields.Count; i++)
                            {
                                item.Add(fields[i], dataReader[fields[i]]);
                            }

                            yield return item;
                        }
                    }
                }
            }
        }

        public static void Main(String[] args)
        {
            foreach (dynamic row in GetData("select * from Shippers"))
            {
                Console.WriteLine("Company name: {0}", row.CompanyName);
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}

Please let me know if this is useful.



来源:https://stackoverflow.com/questions/39839231/stored-procedures-ef-and-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!