我的.NET可能会生锈但我不能在这里找出问题。
我知道它有一个错误,因为我没有检查“null”异常,但我不知道为什么它是null。
tNewObjFolder.cmdSets为null,但是是ICollection,所以我应该能够使用Add将tNewObjCmdSet添加到右边吗?
如果我删除了foreach( * 中的var tCmdSets),它可以工作(但是我很可能没有运行第二个foreach,并且从不尝试向cmdSets.Add添加任何内容功能...
任何帮助都是适当的。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.Data.Objects;
namespace imageController.Models
{
public class settingsModels
{
public class objFolder
{
public decimal id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string bulkDirectory { get; set; }
public ICollection<objCmdSet> cmdSets { get; set; }
}
public class objCmdSet
{
public decimal id { get; set; }
public string name { get; set; }
public string command { get; set; }
public string destination { get; set; }
public string filetype { get; set; }
public decimal? imageId { get; set; }
public decimal? folderId { get; set; }
}
public interface ISettingsService
{
List<objFolder> getFolders();
}
public class settingsServices : ISettingsService
{
private settingsEntities _entities = new settingsEntities();
public List<objFolder> getFolders()
{
ICollection<objFolder> tmpFolders = new Collection<objFolder>();
foreach (var tFolders in _entities.IMG_SETTINGS_FOLDERS)
{
objFolder tNewObjFolder = new objFolder();
tNewObjFolder.id = tFolders.SETTINGS_FOLDER_ID;
tNewObjFolder.name = tFolders.SETTINGS_FOLDER_NAME;
tNewObjFolder.description = tFolders.SETTINGS_FOLDER_DESCRIPTION;
tNewObjFolder.bulkDirectory = tFolders.SETTINGS_FOLDER_BULK;
foreach (var tCmdSets in _entities.IMG_SETTINGS_CMDSETS.Where("it.SETTINGS_FOLDER_ID = @folderid", new ObjectParameter("folderid",tFolders.SETTINGS_FOLDER_ID)))
{
objCmdSet tNewObjCmdSet = new objCmdSet();
tNewObjCmdSet.id = tCmdSets.SETTINGS_CMDSET_ID;
tNewObjCmdSet.name = tCmdSets.SETTINGS_CMDSET_NAME;
tNewObjCmdSet.command = tCmdSets.SETTINGS_CMDSET_COMMAND;
tNewObjCmdSet.destination = tCmdSets.SETTINGS_CMDSET_DESTINATION;
tNewObjCmdSet.filetype = tCmdSets.SETTINGS_CMDSET_FILETYPE;
tNewObjCmdSet.imageId = tCmdSets.SETTINGS_IMAGETYPE_ID;
tNewObjCmdSet.folderId = tCmdSets.SETTINGS_FOLDER_ID;
tNewObjFolder.cmdSets.Add(tNewObjCmdSet);
}
tmpFolders.Add(tNewObjFolder);
}
return tmpFolders.ToList<objFolder>();
}
}
}
}
答案 0 :(得分:1)
你的问题似乎在这里......
tNewObjFolder.cmdSets.Add(tNewObjCmdSet);
你无处可以实现cmdSets集合......
编辑for循环以显示..。
if(tNewObjFolder.cmdSets == null) tNewObjFolder.cmdSets = new Collection<objCmdSet>();
tNewObjFolder.objFolder.Add(tNewObjCmdSet);
或者在objFolder类中添加一个构造函数来初始化构造中的集合......
public objFolder()
{
cmdSets = new Collection<objCmdSet>();
}
答案 1 :(得分:1)
您可以对空集合使用.Add()
,而不是null
。您必须区分这两件事并按照iDevForFun的建议处理null
。