我有2个表之间的多对多关系,我想从联结表中检索数据。
我先分享一些消息来源
数据库表的图像:
EF模型实体的图像:
调试时的错误图片:
我正在使用以下规则或策略
+数据库优先方法
+ EF图
+自定义角色提供程序
问题是,当我尝试从连接表(user_has_role)检索数据时,我正在获取SQL查询而不是数据。###
我得到的SQL查询:
SELECT \ r \ n [Extent1]。[user_id] AS [user_id],\ r \ n [Extent2]。[user_role_name] AS [user_role_name] \ r \ n FROM [dbo]。[user_has_role] AS [Extent1 ] \ r \ n内部联接[dbo]。[user_role]设为[Extent2]处于[Extent1]上。[user_role_id] = [Extent2]。[user_role_id]
这是一些代码
角色提供程序类是从RoleProvider类派生的
public class AppRolesProvider : RoleProvider
所有方法均被覆盖,但只能使用
public override string[] GetRolesForUser(string username)
{
//get all user data from user table for id based on user email
var _user = db.users.Where(u => u.user_email == username).FirstOrDefault();
var _role = (from s in db.users
where (
from c in s.user_role
where s.user_id == _user.user_id
select c
).Any()
select s).ToString();
string[] roleName = { _role };
if (roleName != null)
{
return roleName;
}
else
{
roleName = null;
return roleName;
}
}
我想要针对用户的实际roleName(一个用户有多个角色,也可能有一个)
并尝试从联结表检索数据但得到此查询
“ SELECT \ r \ n [Extent1]。[user_id] AS [user_id],\ r \ n [Extent2]。[user_role_name] AS [user_role_name] \ r \ n FROM [dbo]。[user_has_role] AS [ Extent1] \ r \ n内部联接[dbo]。[user_role] AS [Extent2] ON [Extent1]。[user_role_id] = [Extent2]。[user_role_id] \ r \ n [Extent1]。[user_id] = @ p__linq__0 “
没有数据
这是我在字符串数组中扮演角色的方法
public override string[] GetRolesForUser(string username)
{
//get all user data from user table for id based on user email
int _user_id = Convert.ToInt32(db.users.Where(u => u.user_email == username).Select(i => i.user_id).FirstOrDefault());
// Get role from user_has_role against user id
var _roles = (from _uhr in db.user_has_role
join _r in db.user_role on _uhr.user_role_id equals _r.user_role_id
where _uhr.user_id == _user_id
select new
{
_r.user_role_name
}).ToString();
// store selected
string[] roleName = { _roles };
if (roleName != null)
{
return roleName;
}
else
{
roleName = null;
return roleName;
}
}
答案 0 :(得分:0)
实体表不包含联结表,因为它没有主键。您可以通过在联结表中添加主键来解决此问题,然后更新您的Edmx文件。
更新模型后,您可以使用简单的linq查询从联结表中检索数据。
两种情况之间的区别:
1)如果联结表不包含主键,EF将生成两个具有多对多关系的类
2)如果联结表包含主键,则EF会生成3类:联结表与用户具有一对多关系,与user_role一对多关系
请尝试:
public override string[] GetRolesForUser(string username)
{
//get all user data from user table for id based on user email
int _user_id = Convert.ToInt32(db.users.Where(u => u.user_email == username).Select(i => i.user_id).FirstOrDefault());
// Get role from user_has_role against user id
var _role = db.user_has_role.Where(r => r.user_id == _user_id).Select(r => r.user_role.user_role_name);
// store selected
string[] roleName = _role.ToArray();
if (roleName != null)
{
return roleName;
}
else
{
roleName = null;
return roleName;
}
}