Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 无法将对象添加到我的列表中_Asp.net Mvc_Entity Framework - Fatal编程技术网

Asp.net mvc 无法将对象添加到我的列表中

Asp.net mvc 无法将对象添加到我的列表中,asp.net-mvc,entity-framework,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; } } 错误在这里: if (balanc

我有一个这样的模型:

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; }
}
错误在这里:

 if (balance == null)
    {
      Balance b = new Balance();
      s.Expense.Add(expense);
      s.ApplicationUserId = userId;               
    }
它表示“对象引用未设置为对象的实例” 如果有人能帮助我理解我做错了什么,我会道歉


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

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

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; }
}
公共类平衡
{
公共收支()
{
费用=新列表();
收入=新列表();
}
public int BalanceId{get;set;}
公共列表费用{get;set;}
公共列表{get;set;}
公共字符串applicationSerID{get;set;}
}

Hmmm,你能解释一下为什么不初始化它就不能工作,这样我就能理解我在做什么,因为如果我的模型天平上已经有一个列表,为什么我需要初始化它??抱歉,新手问题
费用
在您初始化之前为空。创建
Balance
的实例不会初始化其属性,除非如上所示在构造函数中初始化它们。
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; }
}