“子查询返回超过 1 个值。这是不允许的。”需要返回一组值

问题描述 投票:0回答:3
var range = this.dataStore.Query<NotificationConfiguration>()
                .Range(p => new NotificationConfigurationViewModel(p, from x in p.Events where !(x.Code == null || x.Code.Equals("")) select x.Code), pageNumber);

return this.View(range);

我有上面的代码,我想返回一个 IEnumerable 但得到一个 每次运行代码时都会出现“子查询返回超过 1 个值。当子查询后面跟有 =、!=、<, <= , >、>= 或子查询用作表达式时,这是不允许的”。我知道查询只想返回一个值,但是如何让它按预期返回一组值?请帮忙!

让我澄清一下......我希望范围包含一个新对象。我有一个正在通过数据库的查询。它返回数据,然后我使用以下视图模型构造函数进行转换:

public NotificationConfigurationViewModel(NotificationConfiguration notification , IEnumerable<string> codes)
{
    Contract.Requires(notification != null);

    this.notification = notification;
    this.codes = codes;
}

每个通知配置都有属性以及与其关联的事件列表。我只需要上述列表中的代码。


再次澄清一下。我希望查询返回一个NotificationConfiguration 和一个IEnumerable(稍后我将使用SB 将其转换为单个字符串)。一旦查询返回这两个项目,我将使用视图模型中的构造函数对其进行转换,以便我可以使用 DataTable 正确显示所有数据。我正在寻找的答案可能非常具体,但我需要了解为什么当我希望它返回 IEnumerable 时会出现子查询错误以及如何修复它。另请注意...根据 .net 文档,代码应该将 IEnumerable 交给我,但由于某种原因它仍然崩溃。这是相关的代码示例:

        [HttpPost]
    public ActionResult Index(DataTableRequest requestedData)
    {
        using (this.dataStore.Session.BeginTransaction())
        {
            return this.dataStore.Query<NotificationConfiguration>()
                          .TableRange(requestedData, p => new NotificationConfigurationViewModel(p, from x in p.Events select x.Code));
        }
    }

.

        public NotificationConfigurationViewModel(NotificationConfiguration notification , IEnumerable<string> events)
    {
        Contract.Requires(notification != null);

        this.notification = notification;
        this.events = events;
    }

.

    [Display(Name = "Events")]
    public virtual string EventTypeCodes
    {
        get
        {
            var codes = new StringBuilder();

            foreach (var item in this.events)
            {
               codes.Append(item + ",");
            }

            return codes.ToString().TrimEnd(',');
        }
    }
c# sql linq
3个回答
2
投票

这里的问题是方法

期望调用者传入以下参数:


0
投票

答案在查询中,而不是数据集中,因此为了给出准确的答案,我们需要查看查询。但一般来说,您可以使用一些结构。您可能有类似 WHERE Id = (SELECT ID FROM Values WHERE DateOFValues BETWEEN FirstDate AND LastDate) 的内容。您想要的是 WHERE ID IN (SELEct... OR WHERE IS = ANY (SELECT... 或子查询,在这种情况下请看这里... http://allenbrowne.com/subquery-01.html (是的,我知道它说的是访问,但 MS SQL 支持这里使用的所有语法。


0
投票

继续假设......这就是你所追求的吗?

如果您尝试创建一堆新对象,则最好在查询的选择部分内完成对象创建。

int pageNumber = 0;
int pageSize = 10;

IQueryable<NotificationConfiguration> configurations = this.dataStore.Query<NotificationConfiguration>();

IList<NotificationConfigurationViewModel> viewModels =
    (from configuration in configurations
     where !string.IsNullOrEmpty(configuration.Code)
     select new NotificationConfigurationViewModel(configuration))
    .Skip(pageNumber * pageSize).Take(pageSize).ToList();

return viewModels;
© www.soinside.com 2019 - 2024. All rights reserved.