简体   繁体   English

C# 实体框架查询结果不正确

[英]C# Entity framework incorrect query result

I am using entity framework in C# with the following code.我在 C# 中使用实体框架,代码如下。

 public List<UserSessionModell> getSessions()
    {
        var result = (from x in db.users
                      from y in db.psw
                      from z in db.users_data
                      from t in db.user_roles
                      from u in db.roles
                      select new UserSessionModell
                      {
                          User_id = x.id,
                          UserName = x.username,
                          Password = y.psw1,
                          Work_id = z.IsEmployedAt,
                          Role = t.role,
                          RoleName = u.id.ToString()
                      }).ToList();

        return result;
    }

The tables in question are connected as follows:有问题的表连接如下: 在此处输入图像描述

Every property receives the correct data except from the "roles" table which always gets the last record in the table.每个属性都接收到正确的数据,除了“角色”表,它总是获取表中的最后一条记录。 Please help, what can be the reason?请帮忙,可能是什么原因?

I think you should join tables.我认为你应该加入表格。

var result = (from user in db.users
                      join psw in db.psw on user.user_id equals psw.user_id 
                      join userdata in db.users_data on userdata.user_id equals psw.user_id 
                      join userrole in db.user_roles on userdata.user_id equals userrole .user_id
                      join role in db.roles on role.id equals userrole .role_id
                      select new UserSessionModell
                      {
                          User_id = user.id,
                          UserName = user.username,
                          Password = psw.psw1,
                          Work_id = userdata.IsEmployedAt,
                          Role = userrole.role,
                          RoleName = role.id.ToString()
                      }).ToList();

1. Attempt to debug this database model in Microsoft SQL Server Management Studio. 1.尝试在Microsoft SQL Server Management Studio中调试这个数据库model。

If there is a problem with syntax SSMS should validate it.如果语法有问题,SSMS 应该对其进行验证。

2. Check if there is more then one role for users. 2. 检查用户是否有多个角色。

Usually, the problem is not in the syntax, rather than in human thoughts about predicted values.通常,问题不在于语法,而在于人类对预测值的想法。

3. Walk slowly, create select from the bottom of the tower. 3.慢慢走,从塔底创建select。

Select values just from roles. Select 值仅来自角色。 If it will be correct then try to go upper levels.如果正确,请尝试 go 上层。 roles with user_roles.具有 user_roles 的角色。 Then roles with user_roles with users.然后角色与 user_roles 与用户。 Maybe there is a problem with values in your database也许您的数据库中的值有问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM