0

How to properly assign my getPur() method to Transaction.PurchasedItems I need a resultset which is a combination of Transaction and PurchasedItems

I'm looking for the result same like in image. Right now I'm getting the desired result with making a new model which contains all the columns. but is it possible to this without making a new model.

enter image description here

What I've tried is below but I'm getting an error on this line

VM.Transaction.PurchasedItems = getPur().ToList().Where(t => t.CustomerId == id).ToList();

Object reference not set to an instance of an object.

Kindly guide me to make this compact.

Models:

    public class Transaction
    {
        public int TransactionId { get; set; }

        public string Progress { get; set; }
        public int ProgressId { get; set; }

        public string Status { get; set; }
        public int StatusId { get; set; }

        public decimal Net { get; set; }

        public DateTime Date_ { get; set; }

        public virtual ICollection<PurchasedItem> PurchasedItems { get; set; }
    }
    public class PurchasedItem
    {
        public int CustomerId { get; set; }
        string Product { get; set; }
        decimal Total { get; set; }
        public string ProductRemarks { get; set; }
    }

Controller

public ActionResult History(int? id)
        {
            CustomerViewModel VM = new CustomerViewModel();
            VM.Transactions = getTransactions().Where(t => t.CustomerId == id);
            VM.Transaction.PurchasedItems = getPur().Where(t => t.CustomerId == id).ToList();

            return View(VM);
        }

public IEnumerable<PurchasedItem> getPur()
        {
            var prod = (from c in db.Customers.Include(c => c.CUSTOMERTYPE)
                        join ch in db.CUSTOMERHEADs.Include(ch => ch.CustomerDatas).Include(ch => ch.Customer).Include(ch => ch.CustomerProgress).Include(ch => ch.CustomerStatu) on c.Id equals ch.CustomerId into l2
                        from ch in l2.DefaultIfEmpty()
                        join sm in db.SalesMen on ch.SalesManId equals sm.MasterId into l1
                        from sm in l1.DefaultIfEmpty()
                        join cd in db.CustomerDatas on ch.id equals cd.Headid into l3
                        from cd in l3.DefaultIfEmpty()
                        select new
                        {
                            cid = c.Id,
                            prod = cd.ProductCode,
                            price = cd.Price,
                            qty = cd.Qty,
                            disc = cd.Disc,
                            amount = cd.Amount,
                            remarks = cd.Remarks,
                            progressid = ch.CustomerProgress == null ? 0 : ch.CustomerProgress.Id,

                        });
            var details = new List<PurchasedItem>();
            foreach (var t in prod)
            {
                details.Add(new PurchasedItem()
                {
                    CustomerId = t.cid,
                    ProgressId = t.progressid,
                    Product = t.prod,
                    Qty = Convert.ToDecimal(t.qty),
                    Price = Convert.ToDecimal(t.price),
                    Disc = Convert.ToDecimal(t.disc),
                    Total = Convert.ToDecimal(t.amount),
                    ProductRemarks = t.remarks,

                });
            }
            return details;
        }

UPDATE

CORRECTION THAT I DID :

public ActionResult History(int? id)
        {
            var details = getTransactions().Where(t => t.CustomerId == id);
            return View(details);
        }

public IEnumerable<Transaction> getTransactions()
        {
            var cust = (from c in db.Customers.Include(c => c.CUSTOMERTYPE)
                        join ch in db.CUSTOMERHEADs.Include(ch => ch.Customer).Include(ch => ch.CustomerProgress).Include(ch => ch.CustomerStatu)
                        .Include(ch => ch.CustomerDatas) on c.Id equals ch.CustomerId into l2
                        from ch in l2.DefaultIfEmpty()
                        join sm in db.SalesMen on ch.SalesManId equals sm.MasterId into l1
                        from sm in l1.DefaultIfEmpty()
                        select new
                        {
                            hid = ch==null?0:ch.id,
                            customerid = c.Id,
                            voucherno = ch.VoucherNo,
                            progress = ch.CustomerProgress.Status,
                            date = ch.Date_==null?DateTime.MinValue : ch.Date_,
                            appointmentDate = ch.Date2_,
                            status = ch.CustomerStatu.Status,
                            sales = sm.Name,
                            notes = ch.Notes,
                            progressid = ch.CustomerProgress == null?0 :ch.CustomerProgress.Id,
                            cd = ch.CustomerDatas.ToList(),

                        });

            var details = new List<Transaction>();

            foreach (var t in cust)
            {
                details.Add(new Transaction()
                {
                    CustomerId = t.customerid,
                    voucherno = t.voucherno,
                    Progress = t.progress,
                    ProgressId = t.progressid,
                    Date_ = t.date,
                    Date2_ = t.appointmentDate,
                    Status = t.status,
                    Salesman = t.sales,
                    AppointmentRemarks = t.notes,
                    PurchasedItems = getPurchase().Where(m => m.Headid == t.hid).ToList(),

                });
            }
            return details;
        }

        public IEnumerable<PurchasedItem> getPurchase()
        {
            var prod = (from c in db.Customers.Include(c => c.CUSTOMERTYPE)
                        join ch in db.CUSTOMERHEADs.Include(ch => ch.CustomerDatas).Include(ch => ch.Customer).Include(ch => ch.CustomerProgress).Include(ch => ch.CustomerStatu) on c.Id equals ch.CustomerId into l2
                        from ch in l2.DefaultIfEmpty()
                        join sm in db.SalesMen on ch.SalesManId equals sm.MasterId into l1
                        from sm in l1.DefaultIfEmpty()
                        join cd in db.CustomerDatas on ch.id equals cd.Headid into l3
                        from cd in l3.DefaultIfEmpty()
                        select new
                        {
                            cid = c.Id,
                            prod = cd.ProductCode,
                            price = cd.Price,
                            qty = cd.Qty,
                            disc = cd.Disc,
                            amount = cd.Amount,
                            remarks = cd.Remarks,
                            progressid = ch.CustomerProgress == null ? 0 : ch.CustomerProgress.Id,
                            hid = cd==null?0:cd.Headid,

                        });
            var details = new List<PurchasedItem>();
            try
            {
                foreach (var t in prod)
                {
                    details.Add(new PurchasedItem()
                    {
                        Headid = Convert.ToInt32(t.hid),
                        CustomerId = t.cid,
                        ProgressId = t.progressid,
                        Product = t.prod,
                        Qty = Convert.ToDecimal(t.qty),
                        Price = Convert.ToDecimal(t.price),
                        Disc = Convert.ToDecimal(t.disc),
                        Total = Convert.ToDecimal(t.amount),
                        ProductRemarks = t.remarks,

                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return details;
        }
Sam
  • 83
  • 7
  • 1
    Obligatory duplicate: [What is a NullReferenceException, and how do I fix it ?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Hans Kesting Jun 06 '18 at 06:24
  • null reference may be because your collection might not be set. nothing to with collections – Mahesh Malpani Jun 06 '18 at 06:25
  • @MaheshMalpani on the same line I'm getting error when setting my method to collection. – Sam Jun 06 '18 at 06:28
  • @HansKesting Thank you for the link but is it possible to let me know where is the issue in below line ? `VM.Transaction.PurchasedItems = getPur().ToList().Where(t => t.CustomerId == id).ToList();` – Sam Jun 06 '18 at 06:33
  • you need to add try catch blocks in both getPur() method and History action method. Now debug the code and check the inner exception to know the exact reason of issue. – Ankit Sahrawat Jun 06 '18 at 06:43
  • Yes. As Ankit correctly pointed out. There will be error in the getPur method. By default IEnumerable will have deferred execution so when you execute toList it will try to execute the getEur method and seems issue there – Mahesh Malpani Jun 06 '18 at 07:28
  • 1
    That is an awful lot of code for a nullreference exception issue. You should be creating a [**Minimal**, Complete, and Verifiable example](http://idownvotedbecau.se/nomcve/) of your problem not code dumps. The title seems odd too, what does any of this have to do with *Use of ICollection*? You should read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Liam Jun 06 '18 at 09:11
  • @Liam Thank you, will follow the link next time. – Sam Jun 06 '18 at 09:25
  • @AnkitSahrawat Thank you. I find out the problem & updated my answer in question. The problem was,i was not setting my Collection inside Method. – Sam Jun 06 '18 at 12:17

1 Answers1

2

It looks you forgot to initialize VM.Transaction itself.

The fix is simple:

VM.Transaction = new Transaction(); // <--- or whatever is needed / suitable
VM.Transaction.PurchasedItems = .....

You can also choose to do it by creating a CustomerViewModel constructor and setting Transaction in that constructor, so then every time you create a CustomerViewModel instance, it will have an initialized Transaction property.

Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Thank you. I find out the problem & updated my answer in question. The problem was,i was not setting my Collection inside Method. also thank you for suggesting construction method. – Sam Jun 06 '18 at 12:17