实体框架多对多条件连接

时间:2012-06-12 01:22:57

标签: c# entity-framework

现在我有3个表:User,Roles和User_Roles,用于多对多关联。我想创建一个搜索函数,该函数接收RoleID列表并返回具有该角色的Users。但如果RoleID列表为空,则应返回所有用户

这是我到目前为止所拥有的......

public static List<User> SearchUser(List<int> roleIDs)
{
    List<User> userList = new List<User>();
    using (var db = new DBContext())
    {
        var users = (
            from u in db.Users
            join ur in db.User_Role
                on u.UserID equals ur.UserID
            join r in roleIDs
                on ur.RoleID equals r
            select u
            ).Distinct().ToList();
    }
    return userList;
}

但是,只有当roleID不为空时,我才能想办法有条件地加入User_Role。

我也尝试了这个,但它没有用。

var users = (from u in db.Users
             from r in roleIDs
             join ur in db.User_Role
                 on u.UserID equals ur.UserID
             where roleIDs.Count == 0 || ur.RoleID == r
             select u
                ).Distinct().ToList();

是否可以在Entity Framework中进行条件连接?

2 个答案:

答案 0 :(得分:1)

分别处理每个案件。

public static List<User> SearchUser(List<int> roleIDs)
{
    using (var db = new DBContext())
    {
        if (roleIDs.Count == 0)
        {
             return db.Users.ToList();
        }

        var users = (
            from u in db.Users
            join ur in db.User_Role
                on u.UserID equals ur.UserID
            join r in roleIDs
                on ur.RoleID equals r
            select u
            ).Distinct().ToList();

        return users;
    }
}

如果连接表未映射为单独的实体,则可以按如下方式简化连接。

public static List<User> SearchUser(List<int> roleIDs)
{
    using (var db = new DBContext())
    {
        if (roleIDs.Count == 0)
        {
             return db.Users.ToList();
        }

        var users = db.Users.Where(u => u.Roles.Any(r => roleIDsContains(r.Id)))
            .Distinct().ToList();

        return users;
    }
}

答案 1 :(得分:0)

我最大的问题是在添加新的搜索条件时保持代码可维护并最小化数据库调用。我最终使用if语句,但直到最后才从数据库加载它。这导致一个大的发送查询。我在最后调用.ToList()强制进行数据库调用。

public static List<user> SearchUser(List<int> roleIDs, List<int> hobbyIDs)
{
    List<User> Users = new List<User>();
    IQueryable<User> tempUsers = null;
    using (var db = new DBContent())
    {
        tempUsers = db.Users;

        if (roleIDs.Count > 0)
        {
            tempUsers = from u in tempUsers
                        join ur in db.User_Role on u.UserID equals ur.UserID
                        join r in roleIDs on ur.RoleID equals r
                        select u;
        }

        if (hobbyIDs.Count > 0)
        {
            tempUsers = from u in tempUsers
                        join uh in db.User_Hobby on u.UserID equals uh.UserID
                        join h in hobbyIDs on uh.HobbyID equals h
                        select u;
        }

        //Go get it from the database
        Users = ((ObjectQuery<User>)tempUsers)
            .Include("Address").Distinct().ToList();
    }
}