我正在创建包含多个发票项目的发票。这是带有多个发票项目的发票外观:
当我刷新整个页面时,它会中断并引发此错误:
Sequence contains more than one element
这是我的代码:
public ActionResult Create(long userId, long invoiceId)
{
ViewBag.InvoiceId = invoiceId;
ViewBag.UserId = userId;
ViewBag.UserId = userId;
var objInvoiceItems = (from i in db.tblinvoiceitems
where i.InvoiceId == invoiceId
select i
).ToList();
var a = (from o in objInvoiceItems
select new InvoiceItemViewModel {
Description = o.DESCRIPTION,
Quantity = o.Quantity,
Rate = o.Rate,
Id = o.ID,
InvoiceId = o.InvoiceId
}).ToList();
var objInvoice = (from i in db.tblinvoices
where i.ID == invoiceId
select i
).ToList();
var obj = (from i in objInvoice
join j in a
on i.ID equals j.InvoiceId
select new InvoiceCreateViewModel
{
AmountPaid = i.AmountPaid,
DueDate = i.DueDate,
InvoiceNo = i.ID,
UserId = i.UserId,
InvoiceItems = a
//InvoiceItems = j
}).SingleOrDefault();
//obj.InvoiceItems = ListInvoiceItems(invoiceId.ToString()).Model;
if (obj == null)
{
obj = new InvoiceCreateViewModel();
}
return View(obj);
}
public class InvoiceCreateViewModel
{
public long? UserId { get; set; }
public double? AmountPaid { get; set; }
public DateTime? DueDate { get; set; }
public double? TotalAmount { get; set; }
public long InvoiceNo { get; set; }
public double? Rate { get; set; }
public string Description { get; set; }
public int? Quantity { get; set; }
public IEnumerable<InvoiceItemViewModel> InvoiceItems { get; set; }
}
它在
SingleOrDefault()
行处中断。发票永远是一个,InvoiceItems可以是多个。我通过jquery在其他函数中处理Add new Invoice Items
,因此在创建没有发票项目的新发票时该函数只会被命中一次。我想退回一张包含多个发票项目的发票;
最佳答案
如果要将类合并为一个模型,可以使用Razor引擎调用该模型,则在视图顶部声明一个viewModel,如下所示
@model ViewModelExample
只需创建一个具有发票和发票项目清单的新模型
public class ViewModelExample
{
public Invoice invoice{get; set;}
public List<InvoiceItems> itemsList{get; set;}
}
像这样将正确的对象分配给数据类型
ViewModelExample
modelExample.invoice = obj
modelExample.itemsList= objInvoice
然后返回modelExample对象,并使用Razer显示
ViewModelExample
类中提供的每个属性的结果。关于c# - Linq-序列包含多个元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39177742/