C# 4.0 转换为视图模型,使用相关实体的EF分部类计算属性返回0
我正在使用EF5,并且有一个新属性,我已经在一个分部类中定义了该属性来扩展基本数据库字段。它需要对相关表中的数据求和C# 4.0 转换为视图模型,使用相关实体的EF分部类计算属性返回0,c#-4.0,entity-framework-5,C# 4.0,Entity Framework 5,我正在使用EF5,并且有一个新属性,我已经在一个分部类中定义了该属性来扩展基本数据库字段。它需要对相关表中的数据求和 [Display(Name = "Qty Allocated")] public decimal QtyAllocated { get { return this.AllocatedContainers == null ? 1 : this.AllocatedContainers.Sum(a => a.Allocate
[Display(Name = "Qty Allocated")]
public decimal QtyAllocated
{
get { return this.AllocatedContainers == null ? 1 : this.AllocatedContainers.Sum(a => a.AllocatedQty); }
//get { return 2;}
}
此属性返回正确的值…但是,如果使用以下方法将其转换为视图模型,则返回的值为0。注意,视图模型继承自类:
public class InventoryContainerDetailListViewModel : InventoryContainerDetail
方法:
public IEnumerable<InventoryContainerDetailListViewModel> ConvertClassToViewModel(IEnumerable<InventoryContainerDetail> entityList)
{
IEnumerable<InventoryContainerDetailListViewModel> itemGrid =
from l in entityList.ToList()
select new InventoryContainerDetailListViewModel()
{
Id = l.Id,
InventoryContainerHeaderId = l.InventoryContainerHeaderId,
PONbr = l.ReceiptDetail == null ? (int?)null : l.ReceiptDetail.PODetail.POHeaderId,
ReceiptDetailId = l.ReceiptDetailId,
ItemId = l.ItemId,
ItemDescription = l.Item.ShortDescription,
QtyInContainer = l.QtyInContainer,
//QtyAllocated = l.AllocatedContainers == null ? 0 : l.AllocatedContainers.Sum(a => a.AllocatedQty),
Location = l.InventoryContainerHeader.Location.DisplayLocation
};
return itemGrid;
}
public IEnumerable ConvertClassToViewModel(IEnumerable entityList)
{
IEnumerable项网格=
从entityList.ToList()中的l开始
选择新的InventoryContainerDetailListViewModel()
{
Id=l.Id,
InventoryContainerHeaderId=l.InventoryContainerHeaderId,
PONbr=l.ReceiptDetail==null?(int?)null:l.ReceiptDetail.PODetail.POHeaderId,
ReceiptDetailId=l.ReceiptDetailId,
ItemId=l.ItemId,
ItemDescription=l.Item.ShortDescription,
QtyInContainer=l.QtyInContainer,
//QtyAllocated=l.AllocatedContainers==null?0:l.AllocatedContainers.Sum(a=>a.AllocatedQty),
位置=l.InventoryContainerHeader.Location.DisplayLocation
};
返回项网格;
}
在该方法中,输入参数entityList确实使用正确的计算值显示每个项目,但在转换后,该值始终为0
我假设这与我从基类继承这一事实有关,但是有人能解释一下吗?我不认为原因是继承。更可能的原因是
AllocatedContainers
是空集合(在创建视图模型实例时,您不会分配它)。感谢您的输入……我想我在概念上理解了您的意思,但不清楚如何实现这一点。创建视图模型实例时如何分配它?您必须从EF加载的真实实体中填充它,或者您必须简单地在该实体上计算它并将其分配给视图模型。它已经在实体中计算(传递到entityList参数中的方法中),我可以在那里看到它。因为这个视图模型继承了实体的QtyAllocated属性,所以我认为它会继续。我无法分配值,因为它是实体上的只读计算属性。因此,我所做的是在视图模型中创建一个新属性,然后从实体中指定它的值,即QuantAlloc=l.QtyAllocated。这似乎是我希望通过从实体继承属性来避免的额外不必要的工作和类维护。