Does this express work for you?
db.Department.Where(d => d.UserDepartmentMapping.Any(ud => ud.User.EmailID == ID)).ToList()
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello everyone! I'm trying to show in my view the assigned departments of logged users. I'm using Forms Authentication and i have the following tables:
I'm using the UserDepartmentMapping table to assign Users to a Department to show them in the Depatments view.
This is my Departments controller where i'm trying to show the assigned departments based on the logged user:
private MVC_DBEntities db = new MVC_DBEntities();
// GET: Departments
public ActionResult Index()
{
var ID = User.Identity.Name;
return View(db.Department.Where(x => x.User.EmailID == ID).ToList());
}
But in my View, i'm getting nothing
This is my Departments model
public partial class Department
{
public Department()
{
this.Product = new HashSet<Product>();
this.UserDepartmentMapping = new HashSet<UserDepartmentMapping>();
}
public int DeptId { get; set; }
public string DepartmentName { get; set; }
public Nullable<int> DepartmentBoss { get; set; }
public virtual ICollection<Product> Product { get; set; }
public virtual User User { get; set; }
public virtual ICollection<UserDepartmentMapping> UserDepartmentMapping { get; set; }
}
And this is my UserDepartmentMapping
public partial class UserDepartmentMapping
{
public int ID { get; set; }
public int UserID { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual User User { get; set; }
}
So, what's the appropriate lambda expression?
Does this express work for you?
db.Department.Where(d => d.UserDepartmentMapping.Any(ud => ud.User.EmailID == ID)).ToList()
A direct relationship between Department and User should not exist since there is a many-to-many between the two tables with the UserDepartmentMapping.
Get started with Entity Framework 6
Relationships, navigation properties, and foreign keys
Querying and Finding Entities