2

我正在开发一个 MVC 4 C# 互联网应用程序。

我有一个 MapLocationCompany 类和一个 MapLocation 类。我在每个 MapLocationCompany 对象之后都有一个 MapLocation 对象列表。

这是我当前的代码:

public class MapLocationCompany
{
    public List<MapLocation> MapLocationList { get; set; }
}

在数据库中创建 MapLocationCompany 后,我希望将 MapLocation 对象添加到此 MapLocationCompany。

在将任何 MapLocation 项目添加到 MapLocationCompany 之前,我要求提供 MapLocationList。

这是我的代码:

public IEnumerable<MapLocation> getMapLocationsForCompany(int id)
{
    MapLocationCompany mapLocationCompany = getMapLocationCompany(id);
    return mapLocationCompany.MapLocationList.ToList(); 
}

我收到此错误:

System.ArgumentNullException was unhandled by user code
Value cannot be null
4

2 回答 2

2

在你的类的构造函数中添加内部列表的初始化

public class MapLocationCompany
{
    [Key]
    public int id { get; set; }
    [HiddenInputAttribute]
    public string UserName { get; set; }
    public string CompanyName { get; set; }
    public double MapStartupLatitude { get; set; }
    public double MapStartupLongitude { get; set; }
    public int MapInitialZoomIn { get; set; }
    public List<MapLocation> MapLocationList { get; set; }

    public void MapLocationCompany()
    {
        MapLocationList = new List<MapLocation>();
    }
}

我们看不到 中的代码是什么getMapLocationCompany(id);,但我想它以某种方式创建了该类的一个实例MapLocationCompany并返回该实例。但是在默认情况下,这个新实例的属性 MapLocationList 设置为 null,因此,如果您尝试使用该属性 ( .ToList()),您会得到一个 Null 引用异常。将上面的代码添加到构造函数有助于避免这个问题。列表仍然是空的,您需要填充它,但保持列表的内部变量已初始化,您可以使用它来添加新元素。

最后一点,该错误是由您对 ToList() 的引用引起的,但MapLocationList已定义为 List,因此您可以将其删除。

于 2014-02-08T09:52:36.193 回答
0

请在调用 ToList() 方法之前检查 NULL。下面是修改后的代码

public IEnumerable<MapLocation> getMapLocationsForCompany(int id)
{
   MapLocationCompany mapLocationCompany = getMapLocationCompany(id);
   if(mapLocationCompany.MapLocationList == null)
   {
       mapLocationCompany.MapLocationList = new List<MapLocation>();
   }

   return mapLocationCompany.MapLocationList;
}
于 2014-02-08T10:05:49.580 回答