JP Edwards
JP Edwards

Reputation: 87

getting a list of values which contain objects which have an id field of x

Sorry - I bet this has been asked lots of times before, but I can't find the answer to my question.

I have two entity framework classes, Companies, and Users. I want to produce a list of companies which have the user allocated to them.

public class FIGcompany
 {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<UserProfile> Users { get; set; }

 }

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public ICollection<FIGcompany> Companies { get; set; }
}

The Linq I am using, I have got as far as:

 var t = db.Companies
            .Any(q => q.Users.Contains(q.Users.

can anyone help me finish it off, I am struggling to get the UserId field from users to do a comparison.

Thanks!

Upvotes: 1

Views: 120

Answers (2)

lisp
lisp

Reputation: 4198

Why query Companies, when you have UserID?

db.Users.First(user => user.UserId == givenId).Companies;

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

This query will return companies which have at least one allocated user:

var companiesWithUsers = db.Companies.Where(c => c.Users.Any());

If you need companies which have user with some id, then:

var companiesForUser = db.Companies.Where(c => c.Users.Any(u => u.UserId == id));

Upvotes: 2

Related Questions