문제

I am developing an MVC 4 C# internet application.

I have a MapLocationCompany class as well as a MapLocation class. I am after each MapLocationCompany object to have a list of MapLocation objects.

Here is my current code:

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

After I have created a MapLocationCompany in the database, I wish to add MapLocation objects to this MapLocationCompany.

Before any MapLocation items have been added to a MapLocationCompany, I am asking for the MapLocationList.

Here is my code:

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

I am getting this error:

System.ArgumentNullException was unhandled by user code
Value cannot be null
도움이 되었습니까?

해결책

Add the initialization of the internal list in the constructor of your class

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>();
    }
}

We can't see what is the code in getMapLocationCompany(id);, but I suppose that it creates, in some way, an instance of the class MapLocationCompany and returns this instance. But in the default situation this new instance has its property MapLocationList set to null and thus, if you try to use that property (.ToList()) you get a Null Reference Exception. Adding the code above to the constructor helps to avoid this problem. The List is still empty and you need to fill it but the internal variable that keeps the list is initialized and you can use it to add new elements.

As a final note, the error is caused by your reference to ToList(), but MapLocationList is already defined as a List so you could remove it.

다른 팁

Please check for NULL before calling ToList() method. Below is the modified code

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

   return mapLocationCompany.MapLocationList;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top