几个小时以来,我一直在尝试各种解决方案,但我无法弄清楚。我在系统中使用自定义成员资格提供程序,因此首先使用代码定义角色表,如下所示:
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 属性始终为空。
UsersInRole 实体映射了这个复合键:
HasKey(compKey => new { compKey.UserId, compKey.RoleId });
我一遍又一遍地检查了这些关系,据我所知,这应该可以正常工作。UserProfile id 字段是 Id,角色 id 字段是 RoleId 作为关系状态。我现在只见树木不见森林!!
任何想法,将不胜感激。