【问题标题】:Convert Linq IQueryable<string> to Linq IQueryable<Custom Type>将 Linq IQueryable<string> 转换为 Linq IQueryable<Custom Type>
【发布时间】:2020-04-23 13:32:30
【问题描述】:

我是使用 Linq 查询的新手,我正在尝试将 IQueryable 转换为自定义类型,但我遇到了问题。请参阅下面的代码;我尝试添加.ToList&lt;&gt;() 我尝试使用.Cast&lt;&gt;(),但没有任何效果。任何见解都会很棒。

错误:无法隐式转换类型 'System.Linq.IQueryable&lt;string&gt;''System.Linq.IQueryable&lt;eSTIP.Models.User&gt;'。显式转换 存在(您是否缺少演员表?)

private static List<UserViewModel> _allBCCUsers = null;
public static List<UserViewModel> AllBCCUsers
{
    get
    {
        if (_allBCCUsers == null)
        {
            eSTIPContext ctx = new eSTIPContext();
            IQueryable<User> users = from u in ctx.BBCRecipient select u.Email; //Error On this line

            _allBCCUsers = new List<UserViewModel>();
            foreach (User u in users)
                _allBCCUsers.Add(new UserViewModel(u));

        }
        return _allBCCUsers;
    }
}

【问题讨论】:

  • 如果你是用户,你可能想要“选择你”。或者,如果您想要电子邮件列表,则在您想要 IQueryable 的行首。但是您的变量减速和您从数据库中选择的内容并不多。
  • @Holger 是的,我想返回电子邮件地址列表。我刚刚接手了这些项目,所以我已经习惯了代码。我实际上不想检查与用户绑定的电子邮件,因为这些地址用于在我的电子邮件列表中包含姓名
  • 我不确定你是否理解我的回答。你知道现在该怎么做吗?将“u.email”更改为“u”,一切都很好。你也可以有一个字符串列表,但你不能填写所有 BCCUsers 列表。
  • @Holger 如果我将 u.email 更改为你,我将如何确保我只获取电子邮件地址
  • 不,你抓住整个用户并使你的代码工作,如果你只想要电子邮件,你必须改变你的整个方法。 UserViewModel存储为User,方法的返回值是UserViewModel的List等。该方法不仅仅是为了返回字符串列表。

标签: c# asp.net-mvc linq-to-sql entity-framework-6 linq-to-entities


【解决方案1】:

编译器会准确解释代码中发生的情况。

使用from u in ctx.BBCRecipient select u.Email,您只能从u(用户?)中选择Email 属性,这是一个字符串,并且您正试图将其存储在 类型的IQueryable 中用户

现在您有两个选择:将您的选择更改为select u(就像@Holger 所说)或更改为IQueryable&lt;string&gt;,但在这种情况下,您需要在您的代码中进行更大幅度的更改。

【讨论】:

  • 当您说更剧烈的代码更改时,您指的是什么?正如我所说,我是新手,所以解释是我现在最好的朋友。
【解决方案2】:

我从您的问题中了解到,您希望返回包含 UserUserViewModel 列表,其中包含 Email

为此,您可以直接从 LINQ 中选择 List&lt;UserViewModel&gt;,无需任何迭代:

private static List<UserViewModel> _allBCCUsers = null;
public static List<UserViewModel> AllBCCUsers
{
    get
    {
        if (_allBCCUsers == null)
        {
            eSTIPContext ctx = new eSTIPContext();
            _allBCCUsers = (from u in ctx.BBCRecipient select new UserViewModel(new User() { Email = u.Email })).ToList();

        }
        return _allBCCUsers;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多