【问题标题】:C# IQueryableto to IEnumerable using Linq expressions and classC# IQueryableto 到 IEnumerable 使用 Linq 表达式和类
【发布时间】:2023-03-18 01:23:01
【问题描述】:

我有一个类应该使用连接从数据库中获取查询结果。

我的班级是:

`
   public class StepTwo 
    {
        public int Id { get; set; }
        public string Party { get; set; }
        public string Currency { get; set; }
        public string Account { get; set; }
        public double? Amount { get; set; }
    }
`

然后我创建了一个返回结果的方法:

  public IEnumerable<StageTwo> StepTwo()
    {
        var queryJoin = (from inn in db.Input.Take(10)
                        join yacc in db.AccY on inn.Action equals yacc.Action
                        orderby inn.Id descending
                        select new 
                        {
                            inn.Id,
                            inn.XParty,
                            inn.Curr,
                            yacc.Action,
                            inn.Amount
                        });
         return queryJoin;
    }

在我没有使用连接的其他方法中,这可以正常工作,但现在无法正常工作。我在return queryJoin; 上有错误消息说明:

`
Cannot implicitly convert type 'System.Linq.IQueryable<<anonymous type: int Id, string XParty, string Curr, string YAction, double? Amount>>' to '
System.Collections.Generic.IEnumerable<Project.StepTwo>'. An explicit conversion exists (are you missing a cast?)`

我知道类名与数据库名有些不同,但我已尝试更改它们以匹配。根据上面的错误,我认为它是别的东西。

任何建议将不胜感激,谢谢。

【问题讨论】:

  • 为什么选择匿名类而不是select new StageTwo { Id = inn.Id ... }

标签: c# entity-framework linq linq-to-sql linq-to-entities


【解决方案1】:

您的错误消息告诉您 queryJoin 是匿名类型,但您试图将其强制为 IEnumerable&lt;StageTwo&gt;,而 C# 无法进行该转换。

queryJoin 是匿名类型的原因是您没有在 linq 查询中定义它。所以要修复它,而不是这个:

select new 
{
    inn.Id,
    inn.XParty,
    inn.Curr,
    yacc.Action,
    inn.Amount
});

你会想要这个:

select new StepTwo 
{
    Id = inn.Id,
    Party = inn.XParty,
    Currency = inn.Curr,
    Account = yacc.Action,
    Amount = inn.Amount
});

【讨论】:

  • 谢谢,解决了!仍然掌握这一点,这是一个很大的帮助。小心点。
  • 乐于助人:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2015-01-29
相关资源
最近更新 更多