2014-02-11 79 views
4

問題函數 下面是我遇到的問題。我不斷收到「序列包含多個元素」的錯誤。這是假設。但是,我不確定如何返回信息,以便我可以使用它。任何幫助,將不勝感激。序列包含多個元素Mvc

EditCountyViewModel是一個小類,它包含public County county public List CountyList . I have also tried changing the Read<> to Read`這是我所有縣信息的基類。

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(); 

     } 

我想我需要另一個類來處理從countyproduct & products表未來的項目。

+0

哪條線給你這個錯誤? – Blorgbeard

+0

返程線。但在註釋掉的代碼中,'editVM.county = multi.Read ().Single();'給了我錯誤 – MaylorTaylor

+0

sql看起來很有趣。 countyproduct.countiesID = countyproduct.countiesID是打算? – smiggleworth

回答

20

SingleOrDefault()確保只有1條記錄返回,並且如果有更多記錄會拋出。如果您只想抓住第一個,請使用FirstOrDefault()

+1

爲什麼這會降低投票率?這是正確的答案。如果您期望多個元素,請勿使用Single或SingleOrDefault。如果您只想要第一個,請使用「First」或「FirstOrDefault」。 –

相關問題