我试图在循环中将对象列表分配给相同类型的Property但我无法分配它。
它始终为null。
public IEnumerable<AppointmentModel> AddProducts (IEnumerable<AppointmentModel> apps)
{
foreach(var app in apps)
{
var products = new List<ProductsEntity>
{
new ProductsEntity {Id = "A", Desc = "ABC"},
new ProductsEntity {Id = "B", Desc = "ABC"},
new ProductsEntity {Id = "C", Desc = "ABC"}
}
app.Products = products; // Values are successfully getting assigned here
}
return apps; //apps.FirstOrDefault().Products is Null here
}
public class AppointmentModel
{
public int Id {get;set;}
public IEnumerable<ProductEntity> Products {get;set;}
}
我已尝试将我的应用转换为IQueryable和IList,但它仅为null
答案 0 :(得分:1)
您已在foreach循环中枚举apps变量。在循环之后,您尝试访问它的第一个元素,但枚举器已经到达列表的末尾。
如果你把它的元素作为一个数组,你将不会遇到这样的问题。
试试这个。
public IEnumerable<AppointmentModel> AddProducts(IEnumerable<AppointmentModel> apps)
{
var appointmentModels = apps as AppointmentModel[] ?? apps.ToArray();
foreach (var app in appointmentModels)
{
var products = new List<ProductsEntity>
{
new ProductsEntity {Id = "A", Desc = "ABC"},
new ProductsEntity {Id = "B", Desc = "ABC"},
new ProductsEntity {Id = "C", Desc = "ABC"}
};
app.Products = products; // Values are successfully getting assigned here
}
return appointmentModels; //apps.FirstOrDefault().Products is Null here
}