我现在已经尝试了几个小时的各种解决方案,而我却无法理解。我在系统中使用自定义成员资格提供程序,因此首先使用代码定义角色表,如下所示:
public class UsersInRole
{
[Key]
public long UserId { get; set; }
[Required]
public UserProfile UserProfile { get; set; }
[Key]
public long RoleId { get; set; }
[Required]
public webpages_Role Role { get; set; }
}
当我编写这个表时,一切看起来都是正确的:
CREATE TABLE [dbo].[UsersInRoles](
[UserId] [bigint] NOT NULL,
[RoleId] [bigint] NOT NULL,
CONSTRAINT [PK_dbo.UsersInRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[UsersInRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.UsersInRoles_dbo.UserProfile_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[UserProfile] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[UsersInRoles] CHECK CONSTRAINT [FK_dbo.UsersInRoles_dbo.UserProfile_UserId]
GO
ALTER TABLE [dbo].[UsersInRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.UsersInRoles_dbo.Roles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([RoleId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[UsersInRoles] CHECK CONSTRAINT [FK_dbo.UsersInRoles_dbo.Roles_RoleId]
GO
奇怪的行为只是填充了UserProfile属性。如果我通过上下文直接加载UsersInRole对象,我会看到相同的行为。
var userInRoles = context.UsersInRoles.ToList();
加载了UserProfile属性,但Role属性始终为null。
UsersInRole实体已映射此复合键:
HasKey(compKey => new { compKey.UserId, compKey.RoleId });
我已经检查了一遍又一遍的关系,据我所知,这应该可以正常工作。 UserProfile id字段是Id,角色id字段是RoleId作为关系状态。我现在看不到树木了!
任何想法都会受到赞赏。
答案 0 :(得分:0)
似乎我在Roles对象定义中犯了一个错误。我现在修复了这个问题,即在角色对象上定义一个foreignkey属性,如:
public class webpages_UsersInRole
{
public long UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
public long RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual webpages_Role Role { get; set; }
}
此类还配置了一个复合键,如:
HasKey(compKey => new { compKey.UserId, compKey.RoleId });
从这里开始,只需加载一个UserProfile,就可以根据需要使用Roles对象正确填充。