无法在我的列表中添加对象

时间:2016-03-25 18:30:05

标签: asp.net-mvc entity-framework

我有这样的模型:

public class Balance
{
    public int BalanceId { get; set; }
    public List<Expense> Expenses { get; set; }
    public List<Income> Incomes { get; set; }
    public string ApplicationUserId { get; set; }
}

这个模型有2个模型的费用和收入清单。

所以我想要的是将费用添加到我的费用清单中,我试图在我的控制器中执行此操作:

public ActionResult Create([Bind(Include = "ExpenseId,TipoDespesaId,DespesaDescricao,DespesaValor,TipoPagamentoId,Data,Comentario")] Expense expense)
    {
        var userId = User.Identity.GetUserId();
        if (ModelState.IsValid)
        {

            var balance = db.Balance.Where(d => d.ApplicationUserId == userId).FirstOrDefault();


            expense.ApplicationUserId = userId;

            if (balance == null)
            {
                Balance b = new Balance();
                s.Expense.Add(expense);
                s.ApplicationUserId = userId;               
            }
            else
            {
                balance.expense.Add(despesa);
            }

            db.Despesas.Add(expense);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.TipoDespesaId = new SelectList(db.TipoDespesas.Where(m => m.ApplicationUserId == userId), "TipoDespesaId", "TipoDespesaNome", despesa.TipoDespesaId);
        ViewBag.TipoPagamentoId = new SelectList(db.TipoPagamentos.Where(m => m.ApplicationUserId == userId), "TipoPagamentoId", "TipoPagamentoNome", despesa.TipoPagamentoId);
        return View(despesa);
    }

错误在于:

 if (balance == null)
    {
      Balance b = new Balance();
      s.Expense.Add(expense);
      s.ApplicationUserId = userId;               
    }

它说&#34;对象引用没有设置为对象的实例&#34; 如果有人可以帮助我理解我做错了什么我是aprecciate

Ps:抱歉我的英语不好但我想了解更多

1 个答案:

答案 0 :(得分:0)

您需要初始化列表属性。一种简单的方法是在您的实体的构造函数中:

public class Balance
{
    public Balance()
    {
        Expenses = new List<Expense>();
        Incomes = new List<Income>();
    }

    public int BalanceId { get; set; }
    public List<Expense> Expenses { get; set; }
    public List<Income> Incomes { get; set; }
    public string ApplicationUserId { get; set; }
}