并非所有代码路径都返回值WCF Service
本文关键字:返回值 WCF Service 路径 代码 | 更新日期: 2023-09-27 18:05:39
你好,我正忙着连接我的SQL数据库到我的WCF RESTful服务。这是我的问题: WebService.Service1.GetAllTrucks(string)': not all code paths return a value
。每个报价都有一个或多个与外键连接的卡车,我希望能够查看每个报价中的每个卡车(我试图在方法:'GetAllTrucks'中做到这一点)。
IService1.cs
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getTrucks")]
List<wsTrucks> GetTrucks();
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getAllTrucks/{truckID}")]
List<wsQuote> GetAllTrucks(string truckID);
Service1.svc.cs
public List<wsTrucks> GetTrucks()
{
NorthwindDataContext dc = new NorthwindDataContext();
List<wsTrucks> results = new List<wsTrucks>();
foreach (tblTruck truck in dc.tblTrucks)
{
results.Add(new wsTrucks()
{
TruckID = truck.ID,
TrucksName = truck.TRUCKNAME
});
}
return results;
}
public List<wsQuote> GetAllTrucks(string truckID)
{
NorthwindDataContext dc = new NorthwindDataContext();
List<wsQuote> results = new List<wsQuote>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
foreach (tblQuote quote in dc.tblQuotes.Where(s => s.ID.ToString() == truckID))
{
results.Add(new wsQuote()
{
QuoteID = quote.ID,
QuoteNumber = quote.QUOTENUMBER
});
return results;
}
}
"
[DataContract]
public class wsQuote
{
[DataMember]
public int QuoteID { get; set; }
[DataMember]
public string QuoteNumber { get; set; }
}
<<p> 卡车/strong> [DataContract]
public class wsTrucks
{
[DataMember]
public int TruckID { get; set; }
[DataMember]
public string TrucksName { get; set; }
}
谢谢。
您应该能够通过将GetAllTrucks(string truckID)方法中的return results
移动到循环之后来解决此问题:
public List<wsQuote> GetAllTrucks(string truckID)
{
NorthwindDataContext dc = new NorthwindDataContext();
List<wsQuote> results = new List<wsQuote>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
foreach (tblQuote quote in dc.tblQuotes.Where(s => s.ID.ToString() == truckID))
{
results.Add(new wsQuote()
{
QuoteID = quote.ID,
QuoteNumber = quote.QUOTENUMBER
});
// return results; <----- HERE! Move this to after the loop
}
return results; // Move it here.
}
问题是,如果列表为空,则会跳过foreach
循环的主体,并且循环后没有返回语句要执行。