不相关实体变量的Linq子查询

时间:2018-11-11 21:01:41

标签: c# sql linq subquery sql-to-linq-conversion

是否可以使用Linq转换/复制以下内容?

DECLARE @UserID INT = 1, @ViewerUserID INT = 1002;

SELECT UGR.*,
CASE
WHEN (
    SELECT subR.[Level]
    FROM UserGameRanks subUGR WITH (NOLOCK)
    INNER JOIN Ranks subR WITH (NOLOCK) ON (subUGR.RankId = subR.Id)
    INNER JOIN Games subG WITH (NOLOCK) ON (subUGR.GameId = subG.Id)
    INNER JOIN Users subU WITH (NOLOCK) ON (subUGR.UserID = subU.Id)
    WHERE subUGR.IsDeleted = 0 AND subU.Id = @ViewerUserID AND subUGR.GameID = UGR.GameId
) > R.[Level] THEN 1
ELSE 0
END AS CanEdit
FROM UserGameRanks UGR WITH (NOLOCK)
INNER JOIN Ranks R WITH (NOLOCK) ON (UGR.RankId = R.Id)
INNER JOIN Games G WITH (NOLOCK) ON (UGR.GameId = G.Id)
INNER JOIN Users U WITH (NOLOCK) ON (UGR.UserID = U.Id)
WHERE UGR.IsDeleted = 0 AND U.Id = @UserID
AND
(
    (
        (@ViewerUserID <> - 1)
        AND
        (UGR.VisibilityId = 1)
    )
    OR
    (
        (UGR.VisibilityId = 2)
    )
    OR
    (
        (UGR.VisibilityId = 0)
        AND
        (@UserID = @ViewerUserID)
    )
)

特别是CASE子查询?我向用户实体类添加了[NotMapped] CanEdit值,但是我不确定如何用一个SQL查询来填充它,而不是先进行初始获取,然后遍历并更新CanEdit。

我已经看过StackOverflow。

任何帮助将不胜感激。

编辑:查看您的答案,我知道如何做到这一点,但我意识到我在问题中做了一些准备。我以上面的查询为例创建了上面的查询,但是现在我发现它与我的问题没有直接关系。我已经更新了SQL部分...

这个想法是,我们可能有许多等级,最低等级为“未设置”,即等级0。因此,如果我玩另一个用户玩的游戏,并且我的等级设置为等级2,则可以分配等级将此用户设置为1。但是在其他游戏上,我也可能是“未设置”(级别0),因此无法编辑他/她的等级。

@CodingYoshi:这是我尝试过的

var viewerQuery = from ugr in context.UserGameRanks
                               join r in context.Ranks on ugr.RankId equals r.Id
                               join g in context.Games on ugr.GameId equals g.Id
                               join u in context.Users on ugr.UserId equals u.Id
                               where (!ugr.IsDeleted) && (ugr.UserId == viewerUserId)
                               select new { UserGameRank = ugr };

            var query = from ugr in context.UserGameRanks
                        join r in context.Ranks on ugr.RankId equals r.Id
                        join g in context.Games on ugr.GameId equals g.Id
                        join u in context.Users on ugr.UserId equals u.Id
                        where (!ugr.IsDeleted) && (ugr.UserId == userId) &&
                        (
                            (viewerUserId != -1 && ugr.VisibilityId == Visibility.RegisteredUsers)
                            ||
                            (ugr.VisibilityId == Visibility.Public)
                            ||
                            (ugr.VisibilityId == Visibility.Hidden && userId == viewerUserId)
                        )
                        select new { GameName = g.Name, Username = ugr.Username, RankName = r.Name, CanEdit = (viewerQuery.Rank.Level > r.Level ? 1 : 0) };

3 个答案:

答案 0 :(得分:1)

也许是这样的:

var users = new List<User>
{
    new User { Id = 1, UserName = "User1", UserTypeId = 1 }, 
    new User { Id = 2, UserName = "User2", UserTypeId = 2 }, 
    new User { Id = 3, UserName = "User3", UserTypeId = 2 }, 
};

var userTypes = new List<UserType>
{
    new UserType { Id = 1, Type = "Admin", Security = 1 }, 
    new UserType { Id = 2, Type = "User", Security = 2  }
};

var userId = 1;

var ViewerUserID = 2;
var viewerSecurity = 
    (from u in users
    join ut in userTypes on u.UserTypeId equals ut.Id
    where u.Id == ViewerUserID
    select ut.Security).FirstOrDefault();

var res = 
    (from u in users
    join ut in userTypes on u.UserTypeId equals ut.Id
    where u.Id == userId || u.Id == -1
    select new
    {
        Id = u.Id,
        UserName = u.UserName,
        CanEdit = viewerSecurity > ut.Security ? 1 : 0
    });
}

class User {
    public int Id {get; set;}
    public string UserName {get; set;}
    public int UserTypeId {get; set;}
}

class UserType {
    public int Id {get; set;}
    public string Type {get; set;}
    public int Security {get; set;}
}

更新: 首先,无需编辑您的问题,因为其他人回答了您的第一个问题,现在他们和我的最初答复毫无意义。 您应该已经提出了一个新问题或更新了这个问题。

这是您已编辑问题的代码:

var res = 
    (from ugr in userGameRanks
    join r in ranks on ugr.RankId equals r.Id
    join g in games on ugr.GameId equals g.Id
    join u in users on ugr.UserId equals u.Id
    where !ugr.IsDeleted    // assuming IsDeleted is of type BIT in your DB
        && u.Id == userId
        && (
                (ViewerUserID != -1 && ugr.VisibilityId == 1)
                || ugr.VisibilityId == 2
                || (ugr.VisibilityId == 0 && userId == ViewerUserID)
            )
    let level =
        (from subUGR in userGameRanks
        join subR in ranks on subUGR.RankId equals subR.Id
        join subG in games on subUGR.GameId equals subG.Id
        join subU in users on subUGR.UserId equals subU.Id
        where !subUGR.IsDeleted 
            && subU.Id == ViewerUserID
            && subUGR.GameId == ugr.GameId
        select subR.Level).FirstOrDefault()

    select new 
    {
        ugr.RankId, 
        ugr.UserId,
        ugr.GameId,
        ugr.IsDeleted,
        ugr.VisibilityId,
        CanEdit = level > r.Level ? 1 : 0
    });

希望这会有所帮助

答案 1 :(得分:0)

我将数据库建模为类以获取正确的语法。不确定我是否正确,但一切都已结束

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int UserID = 1;
            int ViewerUserID = 2;

            DataBase db = new DataBase();

            var resutls = (from subU in db.subU
                           join subUt in db.subUT on subU.Id equals subUt.UserTypeID
                           select new { subU = subU, subUt = subUt })
                           .Where(x => ((x.subU.Id == ViewerUserID) && (x.subUt.Security > x.subU.Security)) || x.subU.Id == -1)
                           .ToList();
        }
    }
    public class DataBase
    {
        public List<Users> subU { get; set; }
        public List<UserTypes> subUT { get; set; }

    }
    public class Users
    {
        public int Id { get; set; }
        public int Security { get; set; }
    }
    public class UserTypes
    {
        public int UserTypeID { get; set; }
        public int Security { get; set; }
    }
}

答案 2 :(得分:0)

一些问题:

1)所有联接都是什么?您应该在模型配置中正确设置导航属性。

2)您得到的查询的CanEdit属性依赖于指定viewerUserId的游戏等级级别,但是似乎指定viewerUserId是可选的。如果未指定或找不到查看者用户,默认行为是什么?我假设CanEdit应该为假。

public class YourResultClass()
{
    public string GameName { get; set; }
    public string UserName { get; set; }
    public string RankName { get; set; }
    public bool CanEdit { get; set; }
}

var targetUserGameRanksQuery = context.Users
    .Where(u => !u.IsDeleted 
        && u.UserId == userId)
    // flatten for use in subsequent join
    .SelectMany(u => u.UserGameRanks);

IQueryable<YourResultClass> query = null;

if(viewerUserId.HasValue)
{
    var viewerGameRanksQuery = context.Users
        .Where(u => !u.IsDeleted 
            && u.UserId == viewerUserId)
        // flatten for use in subsequent join
        .SelectMany(u => u.UserGameRanks);

    var joinQuery = targetUserGameRanksQuery // outer source `o`
        .Join(viewerGameRanksQuery, // inner source `i`
            o => o.GameId,
            i => i.GameId,
            (o, i) => new
            {
                GameName = o.Game.Name,
                TargetUserName = o.Username,
                TargetRankName = o.Rank.Name,
                CanEdit = i.Rank.Level > o.Rank.Level,
                Visibility = o.VisibilityId
            });

    query = joinQuery
        .Where(at =>
            at.Visibility == Visibility.RegisteredUsers

            || (at.Visibility == Visibility.Hidden
                && userId == viewerUserId.Value)

            || at.Visibility == Visibility.Public )
        .Select(at =>
            new YourResultClass()
            {
                GameName = at.GameName,
                UserName = at.UserName,
                RankName = at.RankName,
                CanEdit = at.CanEdit,
            });
}
else
{
    query = targetUserGameRanksQuery
        .Where(ugh => ugr.VisibilityId == Visibility.Public)
        .Select(ugh => new YourResultClass()
        {
            GameName = ugr.Game.Name,
            UserName = ugr.Username,
            RankName = ugr.Rank.Name,
            CanEdit = false,
        });
}