0

我有以下映射:

public webpages_RolesMap()
        {
            // Primary Key
            this.HasKey(t => t.RoleId);

            // Properties
            this.Property(t => t.RoleName)
                .IsRequired()
                .HasMaxLength(256);

            // Table & Column Mappings
            this.ToTable("webpages_Roles");
            this.Property(t => t.RoleId).HasColumnName("RoleId");
            this.Property(t => t.RoleName).HasColumnName("RoleName");

            // Relationships
            this.HasMany(t => t.UserProfiles)
                .WithMany(t => t.webpages_Roles)
                .Map(m =>
                    {
                        m.ToTable("webpages_UsersInRoles");
                        m.MapLeftKey("RoleId");
                        m.MapRightKey("UserId");
                    });

        }

当我使用 Code First 时,这会强制 EF 创建一个如下所示的 pages_UsersInRoles 表:

CREATE TABLE [dbo].[webpages_UsersInRoles](
    [RoleId] [int] NOT NULL,
    [UserId] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [RoleId] ASC,
    [UserId] 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

但是,Microsoft 创建的 SimpleMembership 类执行不指定列名的插入,并且它期望第一列是 UserID,第二个是 RoleId。

INSERT INTO webpages_UsersInRoles VALUES (1,3);

如何使上面的映射创建一个表,其中 UserID 是第 1 列, RoleId 是第 2 列?

请注意,我已经尝试添加这个:

public partial class UsersInRoles
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }
    [Key, Column(Order = 1)]
    public int RoleId { get; set; }

}

但似乎忽略了这一点,仍然以错误的顺序创建列名的多对多。

4

1 回答 1

0

I think you must configure the many-to-many relationship from the other side to change the column order:

// UserProfileMap derived from EntityTypeConfiguration<UserProfile>
public UserProfileMap() 
{
    // ...
    this.HasMany(t => t.webpages_Roles)
        .WithMany(t => t.UserProfiles)
        .Map(m =>
        {
            m.ToTable("webpages_UsersInRoles");
            m.MapLeftKey("UserId");
            m.MapRightKey("RoleId");
        });
}
于 2013-03-18T21:20:53.700 回答