I have 2 simple objects.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public List<Message> Messages { get; set; }
//public int MessageCount { get; set; }
}
Public class Message
{
public int Id { get; set; }
public string Text { get; set; }
}
I need to show MessageCounts for each person which is simply the number of messages a person has wrote. How can I do it?
I have some ideas but I think they will be very slow, since I will need to return a list of persons and on each I need the count.
My Ideas
1- in code
[NotMapped]
public int MessageCount { get {return Messages.Count()}; private set; }
This is the simplest way that I could imagine, but at the same time it seems to be very slow on a large database since for each person it needs to go and fetch the message count separately which is crazy.
2- computed column with a function to return it
It seems like a better plan. right? However, I could not find the whole solution anywhere.
I know I can decorate my property with [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
which will make it read from a computed field, but then how to create a function that returns the value and use that?
I've found something here but he uses the code from the same table which can be done with normal computed fields. I also this post Calculated column in EF Code First but non of the answers was to my question.
--
Considering my question, it should be something that you can seen in many applications. Isn't there any easy and high performance way to do it?
Update
Thanks to people who commented, I guess the best way is to create 2 types, 1 that corresponds to the real person class and using that for normal CRUD actions and the other which is just a view coming from a join to show lists. Any ideas? :)