简体   繁体   中英

How to get the Count of an Entity Framework Junction Table

I have two simple tables, Users and Roles . Both have their own Primary Key called ID along with a few other unique properties that have nothing to do with this question. Both tables also have a virtual IList property of the other. So a User object as the following property:

public virtual IList<Role> Roles { get; set; }

And the Role object has the following property:

public virtual IList<User> Users { get; set; }

Both allow me to navigate from a User to their Role s or from a Role to its User s with ease in C#.

The EntityTypeConfiguration for the Role has nothing specific to the User . However, the User has the following for the Role to create the Junction table:

  this.HasMany(x => x.Roles)
    .WithMany(x => x.Users)
    .Map(x => {
      x.ToTable("UserRole", "xref");
      x.MapLeftKey("UserID");
      x.MapRightKey("RoleID");
    });

This behaves perfectly for everything I needed to do, up to this point. Now, I need a way to query the total number of records in that xref.UserRole table. In SQL I would simply do the following:

SELECT COUNT(*) FROM xref.UserRole

and life would be perfect. But EF takes that Junction table and puts it behind the scenes. I have no way to do something like:

int TotalJoins = db.UserRoles.Count();

I have looked all over here and the web and am not finding anything that is specific to a simple Junction table like this. Other answers have extra fields or is not a true many-to-many join so it will not work in my case.

Is there a way, with some extension method or deeper property on the DbContext to get to that table so I can use it in a Linq query? I know I can write a Stored Procedure, but that seems a bit of a kluge.

I need a way to query the total number of records in that xref.UserRole table

So what you're really looking for is the total number of roles assigned to all users. That could be computed as:

db.Users.Sum(u => u.Roles.Count());

although I'd be surprised if that was actually translated to

SELECT COUNT(*) FROM xref.UserRole

If you want to run that exact query you can always use SqlQuery .

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