How to get a list of lazy lists in the most efficient way?

I have a performance issue with an EF request.

We basically have this:

public class Article
{
    public int ID { get; set; }
    public virtual List<Visit> Visits { get; set; }
}
public class Visit
{
    public int? ArticleID { get; set; }
    public DateTime Date { get; set; }
}

Now I would like to do:

Article a = ...;
vm.Count = a.Visits.Count;

The problem is that from what I can collect, it first causes a selection of the entire list, and then its quantity. When this is done in a loop, this creates a performance problem.

I assumed that this is because the object is "too specific", so I tried to move the call Visits.Countas far as possible to the repository (so we kind of work directly with DbContext). It did not help.

Any suggestions?

+5
source share
3 answers

Assuming your data context has a Visites property:

public class MyDbContext: DbContext
{
    public IDbSet<Article> Articles { get; set; }
    public IDbSet<Visit> Visits { get; set; }
}

:

using (var ctx = new MyDbContext())
{
    var count = ctx.Visits.Where(x => x.ArticleID == 123).Count();
}

, Visites , IEnumerable<T>:

public class Article
{
    public int ID { get; set; }
    public virtual IEnumerable<Visit> Visits { get; set; }
}

.

0

-.

, -, - , , :

In my VisitRepository service, I created a new function GetArticleIDsWithVisit (), which makes a direct sql call through db.SqlQuery, returning a dictionary. The dictionary is cached and used in all places where visit counts are needed.

Not very pretty, but I wrapped it in a repository, so I think that everything is in order.

0
source

All Articles