序列包含多个元素

我有一些问题,通过Linq抓取“RhsTruck”types的列表,并让它们显示。

RhsTruck只是具有适当的品牌,型号,序列等… RhsCustomer具有属性CustomerName,CustomerAddress等…

我不断收到错误“序列包含多个元素”。 有任何想法吗? 我以错误的方式接近了吗?

public RhsCustomer GetCustomer(string customerNumber) { using (RhsEbsDataContext context = new RhsEbsDataContext() ) { RhsCustomer rc = (from x in context.custmasts where x.kcustnum == customerNumber select new RhsCustomer() { CustomerName = x.custname, CustomerAddress = x.custadd + ", " + x.custcity CustomerPhone = x.custphone, CustomerFax = x.custfax }).SingleOrDefault(); return rc; } } public List<RhsTruck> GetEquipmentOwned(RhsCustomer cust) { using (RhsEbsDataContext context = new RhsEbsDataContext()) { var trucks = (from m in context.mkpops join c in context.custmasts on m.kcustnum equals c.kcustnum where m.kcustnum == cust.CustomerNumber select new RhsTruck { Make = m.kmfg, Model = m.kmodel, Serial = m.kserialnum, EquipID = m.kserialno1, IsRental = false }).ToList(); return trucks; } } protected void Page_Load(object sender, EventArgs e) { string testCustNum = Page.Request.QueryString["custnum"].ToString(); RhsCustomerRepository rcrep = new RhsCustomerRepository(); RhsCustomer rc = rcrep.GetCustomer(testCustNum); List<RhsTruck> trucks = rcrep.GetEquipmentOwned(rc); // I want to display the List into a Gridview w/auto-generated columns GridViewTrucks.DataSource = trucks; GridViewTrucks.DataBind(); } 

问题是你正在使用SingleOrDefault 。 只有当集合包含0或1个元素时,此方法才会成功。 我相信你正在寻找FirstOrDefault ,无论集合中有多less元素,它都会成功。

如果序列中有多个元素,则SingleOrDefault方法将引发Exception

显然,您在GetCustomer的查询是find多个匹配项。 因此,您需要优化查询,或者最有可能的方法是检查数据,以了解为什么您会获得给定客户编号的多个结果。

正如@Mehmet所指出的那样,如果你的结果是返回多于一个的elerment,那么你需要查看你的数据,因为我怀疑它的devise不是你有客户共享一个customernumber。

但是,我想给你一个快速的概述。

 //success on 0 or 1 in the list, returns dafault() of whats in the list if 0 list.SingleOrDefault(); //success on 1 and only 1 in the list list.Single(); //success on 0-n, returns first element in the list or default() if 0 list.FirstOrDefault(); //success 1-n, returns the first element in the list list.First(); //success on 0-n, returns first element in the list or default() if 0 list.LastOrDefault(); //success 1-n, returns the last element in the list list.Last(); 

对于更多的Linqexpression式来看看System.Linq.Expressions

仅供参考如果EF Migrations尝试在没有configurationDb的情况下运行(例如,在testing项目中),也可以得到此错误。

追查这几个小时之前,我发现它是一个查询错误,但是,不是因为查询,而是因为它是当试图创buildDb的Migrations踢。