user6084053
user6084053

Reputation:

add a list to the database

Well im doing a application where i have a model like this

public class Saldo
{
    public Saldo()
    {
        Expenses = new List<Expese>();
        Incomes = new List<Income>();
    }

    public int SaldoId { get; set; }
    public List<Expense> Despesas { get; set; }
    public List<Income> Rendimentos { get; set; }
    public string ApplicationUserId { get; set; }
}

what i want to do is add a single expense to the list but it is not working, when i output on the console the count it is always null in the controller im doing this:

 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 s = new Balance();
                s.Expense.Add(expense);
                s.ApplicationUserId = userId;
                db.Balance.Add(s);             
            }
            else
            {
                Balance.Expense.Add(expense);
            }

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

The expense comes from the form and is passed to the Action

I created a new instance of Balance it worked adding the ApplicationUserId but the expense on the list didnt work, can someone explain me why it happen?

Ps: Sorry for my bad english

Upvotes: 0

Views: 99

Answers (1)

Bryan Lewis
Bryan Lewis

Reputation: 5977

Perhaps it's just lost in the translation, but your model doesn't make sense. You have a list of Expense called "Despesas" but in the constructor you call it "Expenses" Whatever that list is called is what you need to add your expense object to. Instead of

s.Expense.Add(expense);

it would be

s.Despesas.Add(expense);

Upvotes: 1

Related Questions