简体   繁体   中英

Ef6: count of the references

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? :)

You will need a relation field between the Message and the user who wrote it, something like this:

Public class Message
{
   public int Id { get; set; }
   public string Text { get; set; }
   public int UserId {get; set; }
}

then when you can count the messages with a simple linq query like this:

context.Messages.Count(m=> m.UserId == id);

linq is optimized to do this the best as possible, but is the database is very large you will need an approach of the optimization by design, and is better to have a persisted field of the messages count and you can increase it with triggers in the publication or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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