序列包含多个元素

我在通过 Linq 获取类型为“ RhsTruck”的列表并显示它们时遇到了一些问题。

RhsTruck 只有适当的制造,型号,系列等..。 RhsCustomer 具有 CustomerName、 CustomerAddress 等属性。

我不断得到错误“序列包含多个元素”(类型为 InvalidOperationException)。有什么想法吗?我是不是理解错了?

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();
}
234437 次浏览

问题是您使用的是 SingleOrDefault。此方法只有在集合恰好包含0或1个元素时才能成功。我相信你正在寻找的 FirstOrDefault将成功无论有多少元素的集合。

如果序列中有多个元素,则 SingleOrDefault 方法抛出一个 Exception

显然,您在 GetCustomer中的查询是查找多个匹配项。因此,您要么需要细化查询,要么很可能需要检查数据,以查看为什么对于给定的客户号码会得到多个结果。

正如@Mehmet 所指出的,如果您的结果返回超过1个元素,那么您需要查看您的数据,因为我怀疑您的客户共享一个客户号码不是设计的。

不过我想给你们简单介绍一下。

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

有关更多 Linq 表达式,请参见 表达式

仅供参考,如果 EF 迁移尝试在没有配置数据库的情况下运行,例如在测试项目中,也可能出现此错误。

在我发现它在一个查询中出错之前,我花了几个小时来研究它,但并不是因为这个查询,而是因为迁移开始尝试创建数据库时出现了错误。

Use FirstOrDefault insted of SingleOrDefault..

如果找不到元素,SingleOrDefault 返回 SINGLE 元素或 null。如果在枚举数中找到2个元素,那么它将抛出您正在看到的异常

FirstOrDefault 返回它找到的 FIRST 元素,如果没有找到元素,返回 null。因此,如果有2个元素与谓词匹配,则忽略第二个元素

   public int GetPackage(int id,int emp)
{
int getpackages=Convert.ToInt32(EmployerSubscriptionPackage.GetAllData().Where(x
=> x.SubscriptionPackageID ==`enter code here` id && x.EmployerID==emp ).FirstOrDefault().ID);
return getpackages;
}


1. var EmployerId = Convert.ToInt32(Session["EmployerId"]);
var getpackage = GetPackage(employerSubscription.ID, EmployerId);