开发者

linq to entities manytomany navigationproperty count

开发者 https://www.devze.com 2023-03-19 23:45 出处:网络
I have the f开发者_如何学运维ollowing two entities: Entity, EntityRelation Where the Entity class has access to the related object through entity.EntityRelations

I have the f开发者_如何学运维ollowing two entities:

Entity, EntityRelation

Where the Entity class has access to the related object through entity.EntityRelations

My goal is to select a list of all Entity objects and the count of related EntityRelation objects. I can do this with:

var results = from e in db.EntitySet.Include("EntityRelations")
    select e;

and then getting EntityRelations.Count in a gridview, but the problem is this is generated some pretty crazy SQL that is not performing due to an outer join with a subselect. My question is: Is there a better way to accomplish my goal?

I am using .NET 3.5 / VS 2008 with SQL Server as a backend.


If you are only using the Count of the EntityRelations and not any of the other information in EntityRelations you could do something like this:

Create a new Class:

class EntityAndCount
{
  public Entity Entity { get; set; }
  public int EntityRelationsCount { get; set; }
}

Return the new class like so:

var results = from e in db.EntitySet
              select new EntityAndCount
              {
                 Entity = e,
                 EntityRelationsCount  = e.EntityRelations.Count()
              };
0

精彩评论

暂无评论...
验证码 换一张
取 消