【问题标题】:The result type 'System.Tuple`3[System.Guid,System.Int32,System.String]' may not be abstract and must include a default constructor结果类型 'System.Tuple`3[System.Guid,System.Int32,System.String]' 可能不是抽象的,必须包含默认构造函数
【发布时间】:2019-11-28 17:06:29
【问题描述】:

是否可以从ObjectContext 对象中读取元组列表?

我在存储过程中有类似这样的数据库查询

SELECT 
    T.Id as Item1, -- this is guid
    T.WorkflowId AS Item2, -- this is int
    T.ActionName AS Item3 -- this is string
FROM 
    MyTable T

我正在尝试像这样阅读它的 c# 代码

var command = context.Database.Connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "[SEQUOIA].[GetWriteOffRequestDetails]";
var objectContext = ((IObjectContextAdapter)context);
context.Database.Connection.Open();

if (reader.NextResult())
{
    // this line is giving error, so basically where it is trying to read/translate the result
    List<Tuple<Guid, int, string>> requestItemActions = objectContext.ObjectContext.Translate<Tuple<Guid, int, string>>(reader).Select(x => new Tuple<Guid, int, string>(x.Item1, x.Item2, x.Item3)).ToList();
}

但是它抛出了这个异常

结果类型 'System.Tuple`3[System.Guid,System.Int32,System.String]' 可能不是 抽象且必须包含默认构造函数。

那么甚至可以像这样读取元组吗?

如果是,谁能指出我错过了什么?

【问题讨论】:

    标签: c# sql sql-server tuples


    【解决方案1】:

    在这种情况下您不能使用tuple,因为tuple class 没有默认构造函数(无参数构造函数).net 框架使用反射自动创建此类型所以它应该有默认构造函数。

    所以这种情况下的解决方案是创建包含这三个属性的类并使用它而不是元组

    public class DataClass
    {
    
        public Guid Item1 { get; set; }
        public int Item2 { get; set; }
        public string Item3 { get; set; }
    }
    
    
    
    
    List<DataClass> requestItemActions = objectContext.ObjectContext.Translate<DataClass>(reader).ToList();
    

    【讨论】:

    • 我实际上是想避免这种解决方案,否则是的,这是标准解决方案。
    • 问题是你应该使用类型有默认构造函数
    【解决方案2】:

    试试

    objectContext.ObjectContext.Select(x => 
       ValueTuple.Create(x.Item1, x.Item2, x.Item3))
    .ToList(); }
    

    【讨论】:

    • 你可以试试 ValueTuple.Create 吗?
    • 是的,它正在加载结果。即使没有带有ValueTuple 的选择部分,它也可以工作,因此仅此一项就可以加载行objectContext.ObjectContext.Translate&lt;ValueTuple&lt;Guid, int, string&gt;&gt;(reader).ToList();。现在唯一的问题是它没有加载值,因此所有 Item1、2 和 3 都是空的,但它确实加载了具有所有空值的行数的对象数。我试图找出可能是什么原因。您知道可能出了什么问题吗?
    • 我不知道,但我的答案是 EF 团队建议的,可能是空的构造函数没有初始化字段。
    • 我都试过了,空的构造函数以及你建议的构造函数,但它们都有相同的问题,它们确实为每一行加载了结果集,但所有值都是空的。让我们看看我是否能找出原因,然后我会告诉你,也会选择你的答案作为正确答案:)
    • 不要使用翻译,只需使用选择,因为我已经更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2010-09-21
    • 2012-11-26
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多