c#-在联接LINQ中使用多个条件.我和
作者:互联网
如何在LINQ联接中使用多个条件,即在我的场景中,我需要从表User中获取所有用户,其中表ID为4,从表UserInGroup中获取,其中UserInGroup是User和Group表之间的中间表,如SQL-T如
select *
from user
where user.userID = userIngroup.userID AND userIngroup.groupID == 4
....
在另一种方法中,我将lambda表达式与LINQ一起使用,如何在下一个中的groupID = 4的情况下应用?
public IEnumerable<User> GetUsersByGroupID(int _groupID)
{
List<User> _listedUsersByGroupID = new List<User>();
using(var _uow = new UserManagement_UnitOfWork())
{
_listedUsersByGroupID = (from _users in _uow.User_Repository.GetAll()
.Include(s=>s.UserInGroup.Select(r=>r.Group))
select _users).ToList();
return _listedUsersByGroupID;
}
}
用户模型
[Table("User")]
public class User
{
public User() { }
[Key]
public int UserID { get; set; }
[StringLength(250)]
[Required]
public string FirstName { get; set; }
[StringLength(250)]
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[StringLength(250)]
[Required]
public string EmailAddress { get; set; }
public ICollection<UserInGroup> UserInGroup { get; set; }
}
UserInGroup模型
[Table("UserInGroup")]
public class UserInGroup
{
public UserInGroup() { }
[Key]
public int UserGroupID { get; set; }
[Required]
public int UserID { get; set; }
[Required]
public int GroupID { get; set; }
public User User { get; set; }
public Group Group { get; set; }
}
组模型
public class Group
{
public Group() { }
[Key]
public int GroupID { get; set; }
[StringLength(250)]
[Required]
public string GroupName { get; set; }
public ICollection<UserInGroup> UserInGroup { get; set; }
}
解决方法:
您只需要添加一个条件即可过滤属于该组4的用户.尝试执行以下操作:
_listedUsersByGroupID = (from _user in _uow.User_Repository.GetAll()
.Include(s=>s.UserInGroup.Select(r=>r.Group))
where user.UserInGroup.Any(ug=>ug.groupID==4)
select _user).ToList();
标签:repository-pattern,entity-framework-6,linq,c,asp-net-mvc 来源: https://codeday.me/bug/20191028/1951309.html