How To Count Associated Entities Without Fetching Them In Entity Framework

后端 未结 6 1613
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 20:50

I\'ve been wondering about this one for a while now, so I thought it would be worth using my first Stack Overflow post to ask about it.

Imagine I have a discussion with

6条回答
  •  广开言路
    2021-01-30 21:13

    If this isn't a one off, and you find yourself needing to count a number of different associated entities, a database view might be a simpler (and potentially more appropriate) choice:

    1. Create your database view.

      Assuming you want all of the original entity properties plus the associated message count:

      CREATE VIEW DiscussionCategoryWithStats AS
      SELECT dc.*,
            (SELECT count(1) FROM Messages m WHERE m.DiscussionCategoryId = dc.Id)
                AS MessageCount
      FROM DiscussionCategory dc
      

      (If you're using Entity Framework Code First Migrations, see this SO answer on how to create a view.)

    2. In EF, simply use the view instead of the original entity:

      // You'll need to implement this!
      DiscussionCategoryWithStats dcs = _repository.GetDiscussionCategoryWithStats(id);
      
      int i = dcs.MessageCount;
      ...
      

提交回复
热议问题