@OwDafuq

Откуда берется новая таблица после переопределения IdentityRole?

Доброго времени суток.
Использую .net core 6, ef core для ms sqlserver.
Переопределенный метод OnModelCreating:
spoiler

protected override void OnModelCreating(ModelBuilder builder)
{
	base.OnModelCreating(builder);
	builder.HasDefaultSchema("Identity");

	builder.Entity<ApplicationUser>(entity =>
	{
		entity.ToTable("Users");
		entity.HasMany(x => x.Roles).WithMany(x => x.Users);
	});

	builder.Entity<ApplicationRole>(entity =>
	{
		entity.ToTable("Roles");
	});

	builder.Entity<ApplicationRoleClaim>(entity =>
	{
		entity.ToTable("RoleClaims");
		entity.HasOne(x => x.Role).WithMany(x => x.RoleClaims).HasForeignKey(x => x.RoleId).OnDelete(DeleteBehavior.Cascade);
	});

	builder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");
	builder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
	builder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
	builder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
}



DbContext объявлен как:
IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, IdentityUserRole<string>, IdentityUserLogin<string>, ApplicationRoleClaim, IdentityUserToken<string>>


Суть вопроса: при создании первой миграции откуда-то появляется дополнительная таблица под именем "ApplicationRoleApplicationUser"
Код создания таблицы:
spoiler

migrationBuilder.CreateTable(
	name: "ApplicationRoleApplicationUser",
	schema: "Identity",
	columns: table => new
	{
		RolesId = table.Column<string>(type: "nvarchar(450)", nullable: false),
		UsersId = table.Column<string>(type: "nvarchar(450)", nullable: false)
	},
	constraints: table =>
	{
		table.PrimaryKey("PK_ApplicationRoleApplicationUser", x => new { x.RolesId, x.UsersId });
		table.ForeignKey(
			name: "FK_ApplicationRoleApplicationUser_Roles_RolesId",
			column: x => x.RolesId,
			principalSchema: "Identity",
			principalTable: "Roles",
			principalColumn: "Id",
			onDelete: ReferentialAction.Cascade);
		table.ForeignKey(
			name: "FK_ApplicationRoleApplicationUser_Users_UsersId",
			column: x => x.UsersId,
			principalSchema: "Identity",
			principalTable: "Users",
			principalColumn: "Id",
			onDelete: ReferentialAction.Cascade);
	});



Код создания таблицы UserRoles:
spoiler

migrationBuilder.CreateTable(
	name: "UserRoles",
	schema: "Identity",
	columns: table => new
	{
		UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
		RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false)
	},
	constraints: table =>
	{
		table.PrimaryKey("PK_UserRoles", x => new { x.UserId, x.RoleId });
		table.ForeignKey(
			name: "FK_UserRoles_Roles_RoleId",
			column: x => x.RoleId,
			principalSchema: "Identity",
			principalTable: "Roles",
			principalColumn: "Id",
			onDelete: ReferentialAction.Cascade);
		table.ForeignKey(
			name: "FK_UserRoles_Users_UserId",
			column: x => x.UserId,
			principalSchema: "Identity",
			principalTable: "Users",
			principalColumn: "Id",
			onDelete: ReferentialAction.Cascade);
	});



Понимаю, что, скорее всего, новая таблица создается из-за того, что в стандартном IdentityUser нет коллекции с ролями пользователя, а я ее добавил, но он не понимает, что уже существует таблица с ролями. Как его заставить писать роли пользователей в родную таблицу?
  • Вопрос задан
  • 49 просмотров
Пригласить эксперта
Ответы на вопрос 1
@oleg_ods
У ApplicationUser и ApplicationRole связь many-to-many. Для ее обслуживания создается дополнительная таблица.

Если хотите использовать для связи таблицу UserRoles это надо указать явно.

Пример из документации:

internal class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options)
        : base(options)
    {
    }

    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasMany(p => p.Tags)
            .WithMany(p => p.Posts)
            .UsingEntity<PostTag>(
                j => j
                    .HasOne(pt => pt.Tag)
                    .WithMany(t => t.PostTags)
                    .HasForeignKey(pt => pt.TagId),
                j => j
                    .HasOne(pt => pt.Post)
                    .WithMany(p => p.PostTags)
                    .HasForeignKey(pt => pt.PostId),
                j =>
                {
                    j.Property(pt => pt.PublicationDate).HasDefaultValueSql("CURRENT_TIMESTAMP");
                    j.HasKey(t => new { t.PostId, t.TagId });
                });
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public ICollection<Tag> Tags { get; set; }
    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public ICollection<Post> Posts { get; set; }
    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public DateTime PublicationDate { get; set; }

    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы