从数据库中获取多个结果集并将结果集转换为所需的类属性

时间:2019-07-19 10:54:37

标签: c# asp.net-mvc entity-framework

我想使用实体框架从数据库检索多个结果集。我在MSDN中获得了此实现,但我想使其通用。

https://docs.microsoft.com/en-us/ef/ef6/modeling/designer/advanced/multiple-result-sets

我的通用类将包含从结果集中进行转换所需的所有列表对象。就像两个结果集Blogsposts一样,我的课程是:

public class ContainerClass
{
   public List<Blogs> blogs { get; set; }
   public List<Posts> posts { get; set; }
}

我修改了以下代码,并坚持将结果集翻译为相应的类。

public T GetMultipleDataset<T>() where T : new() {

            T dataSets = new T();

            int Count = 0;

            var t = typeof(T).GetProperties().Where(a => a.PropertyType.IsGenericType && a.PropertyType.GetGenericTypeDefinition() == typeof(List<>));

            Dictionary<string, string> types = new Dictionary<string, string>();

            foreach (var p in t) {
                var listObjectName = p.PropertyType.GetGenericArguments()[0].Name;
                var propertyName = p.Name;

                types.Add(listObjectName, propertyName);
            }

            // Create a SQL command to execute the sproc
            var cmd = _dbContext.Database.Connection.CreateCommand();
            cmd.CommandText = "[dbo].[GetAllBlogsAndPosts]";

            try {

                _dbContext.Database.Connection.Open();
                // Run the sproc
                var reader = cmd.ExecuteReader();

                do {

                    Type typ = dataSets.GetType().GetProperty(types.ElementAt(Count).Value).GetType();

                    var p = typ.MakeGenericType(new Type[] { typ });

                    var o = Activator.CreateInstance(p);

                    // Read Blogs from the first result set
                    var blogs = ((IObjectContextAdapter)_dbContext)
                        .ObjectContext
                        .Translate<>(reader, types.ElementAt(Count).Value, MergeOption.AppendOnly);  //stuck here

                    // Move to second result set and read Posts
                    reader.NextResult();
                    Count++;

                } while (reader != null);
            }
            finally {
                _dbContext.Database.Connection.Close();
            }

            return dataSets;
        }

我想将结果集转换为相应的ContainerClass的Blog和帖子。有可能吗?

0 个答案:

没有答案