user1490835 user1490835 - 9 months ago 68
C# Question

Linq - Sequence contains more than one element

i am creating an invoice with multiple invoice items. this is how the invoice looks with multiple invoice items:
enter image description here

when i do a refresh of the whole page, it breaks and throws this error:

Sequence contains more than one element

this is my code:

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

var a = (from o in objInvoiceItems
select new InvoiceItemViewModel {
Description = o.DESCRIPTION,
Quantity = o.Quantity,
Rate = o.Rate,
Id = o.ID,
InvoiceId = o.InvoiceId

var objInvoice = (from i in db.tblinvoices
where i.ID == invoiceId
select i

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
//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; }


It's breaking at the line
. Invoice is always one and InvoiceItems can be multiple. I am handling
Add new Invoice Items
in a different function through jquery so this function only gets hit once when creating a new invoice with no invoice items.

I want to return one invoice with multiple invoice items;


If you want to combine classes into a single that model that can be called using the Razor engine declare a viewModel at the top of your view like so

@model ViewModelExample

Simply create a new model that will have an invoice and a list of invoice items

public class ViewModelExample
   public Invoice invoice{get; set;}
   public List<InvoiceItems> itemsList{get; set;}

Assign to the datatype ViewModelExample the correct objects like so

modelExample.invoice = obj
modelExample.itemsList= objInvoice

Afterwards return the modelExample object and use Razer to display the result for each of the properties provided in the ViewModelExample class