【问题标题】:Sequence contains more than one element Mvc序列包含多个元素 Mvc
【发布时间】:2014-03-09 22:34:21
【问题描述】:

问题函数 以下是我遇到问题的功能。我不断收到“序列包含多个元素”错误。这是假设的。但是,我不确定如何返回信息以便我可以使用它。任何帮助,将不胜感激。

EditCountyViewModel 是一个小类,其中包含 public County countypublic List CountyList. I have also tried changing the Read<> toRead`,它只是我所有县信息的基类。

public EditCountyViewModel FindByCounty(string countyName)
        {
            var parameters = new DynamicParameters();
            parameters.Add("@CountyName", value: countyName);

            var query = @"SELECT counties.id
                            , counties.CountyName
                            , counties.Website
                            , counties.Address
                            , counties.City
                            , counties.State
                            , counties.PhonePrimary
                            , counties.PhoneAlt
                            , counties.RecordsOnline
                            , counties.BackToYear
                            , counties.Cost
                            , products.ProductName
                            , products.Description
                            , countyproduct.TurnTime_MinHours
                            , countyproduct.TurnTime_MaxHours
                            , countyproduct.Price
                        FROM
                            counties, countyproduct, products
                        WHERE
                            counties.CountyName = @CountyName AND countyproduct.countiesID = countyproduct.countiesID AND countyproduct.productsID = products.ID;";

            //using (var multi = this.db.QueryMultipl(query, new { countyName }))
            //{
            //    EditCountyViewModel editVM = new EditCountyViewModel();
            //    editVM.county = multi.Read<County>().Single();
            //    return editVM;
            //}
            return this.db.Query<EditCountyViewModel>(query, parameters).SingleOrDefault();

        }

我想我需要另一个类来处理来自countyproductproducts 表的项目。

【问题讨论】:

  • 哪一行给你这个错误?
  • 返回行。但是在注释掉的代码中,editVM.county = multi.Read&lt;County&gt;().Single(); 给了我错误
  • 这个 sql 看起来很有趣。 countyproduct.countiesID =countyproduct.countiesID 是这样的吗?

标签: c# mysql asp.net-mvc


【解决方案1】:

SingleOrDefault() 确保只返回 1 条记录,如果有更多则抛出。如果您只想抢到第一个,请使用FirstOrDefault()

【讨论】:

  • 为什么这被否决了?这是正确的答案。如果您期望多个元素,请不要使用SingleSingleOrDefault。如果您只想要第一个,请使用FirstFirstOrDefault
猜你喜欢
  • 1970-01-01
  • 2015-01-21
  • 2013-02-07
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多