0

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. 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)

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.

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...

Kendrick
  • 3,747
  • 1
  • 23
  • 41
  • 1
    `FK in parent` You mean your FK is in the childCollection entity object or the `Parent` object? – jamesSampica Feb 14 '14 at 02:34
  • No, I meant each child object has a fk ChildStatusID that specifies its status. Good question. I'm not sure I could have made that less clear... – Kendrick Feb 14 '14 at 03:13

1 Answers1

2

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;
}
Shay
  • 1,680
  • 2
  • 26
  • 39
  • You understand it correctly. But I'm not sure how to tie that back into the parent object in an EF friendly manner. – Kendrick Feb 14 '14 at 03:22
  • @Kendrick How do you mean? As a calculated property? – jamesSampica Feb 14 '14 at 04:07
  • Not calculated, per se, just retrieved from the database as part of building the object. The only "calculation" is finding the child object with max date. – Kendrick Feb 14 '14 at 15:08
  • @Kendrick if your objects are EF auto generated (aka model first) you can use an extension class (using `partial`). very similar to the following [answer](http://stackoverflow.com/a/1131928/264672) but with a query instead of just calculating the value. – Shay Feb 19 '14 at 00:58
  • I'm working from code first, but I think this may still be the solution. It's possible I'm simply not giving EF enough credit and expecting this to be more complicated than it actually is. I'll give it a shot and let you know how it goes. – Kendrick Feb 19 '14 at 17:34