How to count entities properly
I have a method which has an attribute "user" and I'm trying to check if he's already in a team of the given "course"
private static bool UserIsInTeamOfCourse(Course course, User user)
{
var count = course.Teams.Count(x => x.Users.Contains(user));
if (count > 0)
{
return true;
}
return false;
}
But it doesn't work. I made a custom Equals method in my User model, but it still don't work. [EDIT] It always counts zero entries, but there have to be at least one entry.
public override bool Equals(object obj)
{
return UserId == ((User)obj).UserId;开发者_Python百科
}
bool isUserInAnyTeam = course.Teams.Any(t => t.Users.Any(u => u.Id == user.Id));
This is LINQ to Objects because you are querying on the Teams
collection in memory. So it assumes that the Teams
collection is already loaded or will be lazily loaded. If it's not loaded and you don't use lazy loading you can create a database query on the collection:
In EF 4.1 with DbContext:
bool isUserInAnyTeam = dbContext.Entry(course).Collection(c => c.Teams).Query()
.Any(t => t.Users.Any(u => u.Id == user.Id));
Or in EF 4.0:
bool isUserInAnyTeam = course.Teams.CreateSourceQuery()
.Any(t => t.Users.Any(u => u.Id == user.Id));
Teams
must be of type EntityCollection<Team>
in the last case.
Another way is to query from scratch:
bool isUserInAnyTeamOfCourse = context.Courses.Any(
c => c.Id == course.Id && c.Teams.Any(t => t.Users.Any(u => u.Id == user.Id)));
Assuming there is a many to many relationship betweens teams and users and a user will not be part twice of the same team.
var count = (from c in context.Teams
from u in c.Users
where u.Id == 1
select c.Id).Count();
Entity framework can not translate your c# code in which you've overriden equals to a sql function.
Instead of comparing custom objects compare userID (which is probably int or other simple type)
private static bool UserIsInTeamOfCourse(Course course, User user)
{
return course.Teams.Where(team => team.Users.Any(u => u.userID == user.userID)).Count() > 0;
}
精彩评论