Richasantos
Richasantos

Reputation: 616

Join LINQ tables based on model definition

I want to join tables using linq, based on the definition of the model. Example of what I want:

from department in User.departments...

My classes are:

USER CLASS:

public class User
{
    public User() {
        Departments = new List<Department>();
    }
    public int UserId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<Department> Departments { get; set; }
}

DEPARTMENT CLASS:

public class Department
{
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set; }
    public virtual User User { get; set; }
}

I'm creating inside the user class this:

public bool hasDepartment(int DepartmentId, int UserId)
{
    var test = from department in User.departments
    //...
}

But I'm having this message: 'User' does not contain a definition for 'departments'.

I'm creating a ASP.NET MVC application. Am I doing anything wrong?

Upvotes: 0

Views: 83

Answers (3)

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

User' does not contain a definition for 'departments'

Issue exist since Departments is not a static collection inside User class, so you need an object of User class to access the Departments ICollection property

Since in the User class, modify the access as follows:

var test = from department in Departments Or

`var test = from department in this.Departments`

Idea is same, to have object based access instead of static access

Upvotes: 1

public bool hasDepartment(int DepartmentId, int UserId)
{
    var test = from department in Departments
    ...
}

Upvotes: 0

PiotrWolkowski
PiotrWolkowski

Reputation: 8792

If the spelling of your message is exact then the reason for the error must be departments with lower d. Your 'Departments' property in the class definition is capital D.

Upvotes: 1

Related Questions