简体   繁体   English

获取最新子项的属性作为实体框架(EF)中的计算属性

[英]Get property from latest child as calculated property in Entity Framework (EF)

Database background: 数据库背景:

-Parent
|- ChildCollection (with dates)
 |- ChildStatus (FK in Child object.  ChildStatus is a lookup value)

I use child in the context of the database relation. 我在数据库关系的上下文中使用child。 Inheritance is not a factor here. 继承不是这里的一个因素。

What I would like is, in my parent object, to get from the database and store the latest date in the child collection, and the status attached to that child object. 我想要的是,在我的父对象中,从数据库中获取并将最新日期存储在子集合中,以及附加到该子对象的状态。 The ultimate goal would be to be able to say Parent.LastDate (as a DateTime object) and Parent.LastStatus (as a ChildStatus object) 最终目标是能够说Parent.LastDate (作为DateTime对象)和Parent.LastStatus (作为ChildStatus对象)

I've found a number of posts on how to deal with a calculated field from within the parent, or a count for the number of children, but not a way to actually eagerly load a reference to the grandchild entity without explicitly loading the child collection. 我已经找到了一些关于如何处理父项内的计算字段或者子项数的计数的帖子,但没有找到实际急切加载对孙子实体的引用而不显式加载子集合的方法。

I'd like the two objects available to me if I simply pass Parent as my model in MVC without including the child entities. 如果我简单地将Parent作为我的模型在MVC中传递而不包括子实体,我希望这两个对象可用。

I guess the better question is "how should I be doing this?" 我想更好的问题是“我该怎么做?” Is this a case where I should create a view and populate the additional properties in the view? 这是我应该创建视图并在视图中填充其他属性的情况吗? I haven't worked with views yet, so this may be a simple misunderstanding of the ideal architecture on my part... 我还没有处理过观点,所以这可能是对我理想架构的一个简单误解......

If I understood it right, this is how your code should look like: 如果我理解正确,这就是你的代码应该是这样的:

var latestChild = Parent.ChildCollection.OrderByDescending(c => c.Date).FirstOrDefault();

if(latestChild != null) 
{
    Parent.LastDate = latestChild.Date;
    Parent.LastStatus = latestChild.ChildStatus;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM