我正在尝试将MainFolderDisplay
内的var mainFolder = new MainFolderDisplay();
mainFolder.StorageFile.Add(new StorageFile
{
AwsUniqueFileName = "asasas",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "",
UserId = 0,
});
的值设置为列表。但是问题是我越来越像波纹管一样异常。我在这里做什么错了?
System.NullReferenceException:'对象引用未设置为 对象的实例。'
控制器:
using Test.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Test.ViewModels
{
public class MainFolderDisplay
{
public int MainFolderId { get; set; }
public string MainFolderName { get; set; }
public int UserId { get; set; }
public List<SubFolder> SubFolders { get; set; }
public List<StorageFile> StorageFile { get; set; }
}
public class SubFolderDisplay
{
public int SubFolderId { get; set; }
public string SubFolderName { get; set; }
public int MainFolderId { get; set; }
public List<StorageFile> StorageFile { get; set; }
}
public class StorageFileDisplay
{
public int FileId { get; set; }
public string AwsUniqueFileName { get; set; }
public string UserDisplayFileName { get; set; }
public int UserId { get; set; }
public int FolderType { get; set; }
public int RelatedFolderId { get; set; }
}
}
型号:
db.Movieinfo.insert({
"MovieID":1,
"MovieName":"iron man",
"Actor":"Robert downey",
"ReleaseDate":2008,
"GotOscars":1,
})
答案 0 :(得分:1)
StorageFile列表未初始化。
mainFolder.StorageFile = new List<StorageFile>();
我建议将此属性重命名为StorageFiles以暗示它是一个集合。
mainFolder.StorageFiles = new List<StorageFile>();
答案 1 :(得分:0)
在使用之前,您的“ StorgaeFile”属性未初始化:
var mainFolder = new MainFolderDisplay();
mainFolder.StorageFile = new List<StorageFile>
{
new StorageFile
{
AwsUniqueFileName = "asasas",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "",
UserId = 0,
}
};
更好的方法是更改“ MainFolderDisplay”类实现以处理初始化:
public class MainFolderDisplay
{
private List<StorageFile> _storageFile;
public int MainFolderId { get; set; }
public string MainFolderName { get; set; }
public int UserId { get; set; }
public List<StorageFile> StorageFile
{
get => _storageFile ?? (_storageFile = new List<StorageFile>());
set => _storageFile = value;
}
}
现在不用担心了:
mainFolder.StorageFile.Add(
new StorageFile
{
AwsUniqueFileName = "asasas",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "",
UserId = 0,
});