处理 EF 存储过程的多个结果集的通用方法

2024-05-09

  • EF 6、.NET 4.51

我正在尝试构建一个通用帮助程序类,它将帮助我将每个结果集“翻译”为类型安全类,如此处所述使用 SqlQuery 处理存储过程的多个结果 https://stackoverflow.com/questions/25304791/handle-multiple-result-from-a-stored-procedure-with-sqlquery/25305607#25305607

对于我的解决方案,我想将以下内容传递给我的帮助器类(MultiResultsetsHelper):

  1. 通用返回类型
  2. 对象上下文
  3. 数据读取器
  4. 班级类型列表in order返回的结果集的数量

然后让辅助类完成填充 1 的繁重工作。下面是到目前为止的代码:

结果类

public class Set1ReturnDto
{
    public int CruiseCount { get; set; }
    public string DisplayText { get; set; }
    public int DisplayValue { get; set; }
}

public class Set2ReturnDto
{
    public string DepartingFrom { get; set; }
    public string Port_Code { get; set; }
}

public class DummyReturnDto
{
    public DummyReturnDto()
    {
        Set1 = new List<Set1ReturnDto>();
        Set2 = new List<Set2ReturnDto>();
    }

    public List<Set1ReturnDto> Set1 { get; set; }
    public List<Set2ReturnDto> Set2 { get; set; }
}

低级数据库调用

    public static DummyReturnDto DonoUspGetSideBarList(DbContext aDbContext, out int aProcResult)
    {
        SqlParameter procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output };

        DbCommand dbCommand = aDbContext.Database.Connection.CreateCommand();
        dbCommand.Parameters.Add(procResultParam);
        dbCommand.CommandText = "EXEC @procResult = [dbo].[usp_GetSideBarList] ";
        dbCommand.Transaction = aDbContext.Database.CurrentTransaction.UnderlyingTransaction;

        DbDataReader reader = dbCommand.ExecuteReader();
        aProcResult = -1;

        // Drop down to the wrapped `ObjectContext` to get access to the `Translate` method
        ObjectContext objectContext = ((IObjectContextAdapter)aDbContext).ObjectContext;

        List<Type> containedDtos = new List<Type>
                                   {
                                       typeof (List<Set1ReturnDto>), 
                                       typeof (List<Set1ReturnDto>)
                                   };

        return MultiResultsetsHelper.Process<DummyReturnDto>(reader, objectContext, containedDtos);
    }

返回的结果数据集是:

助手类

public static class MultiResultsetsHelper
{
    /// <summary>
    ///     Given a data reader that contains multiple result sets, use the supplied object context to serialise the
    ///     rows of data in the result set into our property.
    /// </summary>
    /// <typeparam name="T">Type of the containing object that contains all the various result sets.</typeparam>
    /// <param name="aDbReader">Database reader that contains all the result sets returned from the database.</param>
    /// <param name="aObjectContext">Data context associated with the data reader.</param>
    /// <param name="aContainedDataSetReturnedTypes">
    ///     List of types in order of which the result sets are contained within the
    ///     data reader. We will serilize sequentially each result set the data reader contains
    /// </param>
    /// <returns>Retuns an object representing all the result sets returned by the data reader.</returns>
    public static T Process<T>(DbDataReader aDbReader, ObjectContext aObjectContext, List<Type> aContainedDataSetReturnedTypes) where T : new()
    {
        //What we will be returning
        T result = new T();

        for (int datasetNdx = 0; datasetNdx < aContainedDataSetReturnedTypes.Count; datasetNdx++)
        {
            //Advance the reader if we are not looking at the first dataset
            if (datasetNdx != 0)
                aDbReader.NextResult();

            //Get the property we are going to be updating based on the type of the class we will be filling
            PropertyInfo propertyInfo = typeof (T).GetProperties().Single(p => p.PropertyType == aContainedDataSetReturnedTypes[datasetNdx]);

            //Now get the object context to deserialize what is in the resultset into our type
            var valueForProperty = aObjectContext.Translate <aContainedDataSetReturnedTypes[datasetNdx]> (aDbReader);

            //Finally we update the property with the type safe information
            propertyInfo.SetValue(result, valueForProperty, null);
        }
        return result;
    }
}

但目前我无法编译它。

错误 2 运算符“

有人可以帮忙吗?最终,它与我们如何使用反射和传入的 ContainedDataSetReturnedTypes 有关。我很乐意改变一切,只要调用 MultiResultsetsHelper.Process() 仍然很容易


这段代码:

aObjectContext.Translate<aContainedDataSetReturnedTypes[datasetNdx]>

不起作用,因为泛型类型参数总是在编译时解析。你不能通过Type运行时的实例。

您仍然可以调用泛型方法,但您必须使用反射 https://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

处理 EF 存储过程的多个结果集的通用方法 的相关文章

随机推荐

  • 如何在 Angular-4 中的 md-progress-spinner 中设置文本

    在 Angular 4 中 我像这样设置进度旋转器
  • 重复的 AssemblyVersion 属性

    我有一个项目在编译时生成以下错误 错误 CS0579 重复的 AssemblyVersion 属性 我已经检查过文件AssemblyInfo cs看起来那里没有重复 I found MSDN 上的这篇文章 http social msdn
  • ListView onClick 事件不会因链接的电子邮件地址而触发

    我有一个直接的 ListView 带有 ListAdapter 和列表的自定义 onItemClick 方法 我的 ListView 项目可单击以执行其他功能 但是 我的一些 ListView 元素包含一个电子邮件地址should也可以点击
  • 如何读取 Google 表格中单元格的颜色

    我正在使用 Python Google Sheets API 并且我想读取单个单元格的颜色 我已阅读文档 但我只能找到有关如何从单元格检索文本的信息 而不是颜色格式的信息 您可以使用方法 电子表格 get https developers
  • 终端中的 Visual Studio Code Java 路径

    我刚刚开始使用 Visual Studio Code 并用 Java 创建了一个简单的 Hello World 程序 它打印Hello World就像它应该的那样 但我也得到了一些路径 例如 usr lib jvm java 11 open
  • R 中有没有快速替换列值的方法?

    假设我们有一个包含数值的数据框 如下所示 Temperature Height 32 157 31 159 33 139 我想更换Height价值观与pic 00001 pic 00002等等 最终结果是 Temperature Heigh
  • Java:getTimeZone不返回默认值

    我有以下指示 TimeZone zone TimeZone getTimeZone Asia Toyo 显然 它应该返回 null 但它会返回默认时区 这不是我的情况所需的行为 来自 Java 文档 返回指定的TimeZone 或 GMT
  • 为什么超过44个字符时打印随机符号

    我正在从 C 编程 现代方法 一书中学习 C 现在我正在进行有关数组的练习 练习之一是编写一个过滤器 以不同的方式打印输入消息 到目前为止 参见下面的代码 一切正常 直到字符数超过 44 然后它打印随机符号 如果字符数低于 44 则一切正常
  • 如何在 firebase 中设置重复项目? [复制]

    这个问题在这里已经有答案了 我想在 firebase 中创建一个重复的项目 这样我就不必经历添加 firebase 功能和通知等的麻烦 如果可以的话 我会删除所有身份验证用户 以便为实际的应用程序做好准备 但我无法做到这一点 那么 如何在没
  • 使用什么来生成包含动态生成的条形码的 pdf 文档(Java)?

    我的要求要求生成包含任意文本和条形码的 pdf 文档 我有相关的question https stackoverflow com q 6625849 59470它解决了pdf生成部分 但在这里我想知道如何在Java中将条形码合并到pdf中
  • Find() 的 Javascript 代码优化

    我有 C 代码 可以在 SQL 中运行查询并返回大约 2000 行 然后创建一个Treeview控件并添加到我的主页 这几乎是立即完成的 这很好 var orgId select name ctl00 PageContent Functio
  • 如何更改 Google 表格中图表的背景不透明度?

    我想在 Google 表格中设置 Google 图表的透明度或不透明度 就像在 Microsoft Excel 中一样 将图像设置在文本后面 以便文本仍然可读 不过好像该功能不起作用 功能预览 http drive google com f
  • 保存到服务器后,隐藏字符“\u0”添加到文件中

    我正在使用 Apache 服务器为 Web 开发网站提供服务 这样我就可以不断保存和编辑文件 我使用 Gulp for Sass 来连接和丑化 css 和 js 文件 一个月前 我的 js 和 css 文件遇到问题 似乎在文件下面添加了随机
  • 在Web应用程序中调用phonegap插件功能

    我正在构建我的第一个phonegap应用程序 当我打开该应用程序时 我立即将用户重定向 window location 到托管我的网络应用程序的服务器 是否可以从那里加载phonegap 插件 因为 deviceready 事件没有触发 我
  • PIL 不保存透明度

    from PIL import Image img Image open 1 png img save 2 png 第一张图像具有透明背景 但是当我保存它时 透明度消失了 背景为白色 我究竟做错了什么 可能图像已被索引 PIL 中的模式 P
  • Mnesia:如何同时锁定多行,以便我可以写入/读取一组“一致”的记录

    我多么希望我一开始就能表达我的问题 取一个包含 26 个键 a z 的表 并让它们具有整数值 创建一个流程 哎哟 一遍又一遍地做两件事 在一笔交易中 写入随机值a b and c使得这些值always总和为 10 在另一个事务中 读取值a
  • 交换两个向量之间的值,使两个向量的 max_element 之和最小

    这是 Codechef 的问题 但请耐心等待 https www codechef com ZCOPRAC problems ZCO16001 https www codechef com ZCOPRAC problems ZCO16001
  • SavedStateHandle不持久化数据

    我按照下一页中的说明创建了一个 viewModel 但是SavedStateHandle当我关闭应用程序并再次打开它时不起作用 这是页面 ViewModel 的已保存状态模块 https developer android com topi
  • 图片无法直接上传到相册

    我正在开发上传图片文件的应用程序 但图片不能直接上传到相册 上传之前始终必须经过批准 如何解决这个问题 问题 您想将这些照片添加到您的相册吗 下面的照片是从另一个应用程序上传的 您需要批准它们 你需要user photos允许直接上传到相册
  • 处理 EF 存储过程的多个结果集的通用方法

    EF 6 NET 4 51 我正在尝试构建一个通用帮助程序类 它将帮助我将每个结果集 翻译 为类型安全类 如此处所述使用 SqlQuery 处理存储过程的多个结果 https stackoverflow com questions 2530