У меня были отношения «Один ко многим» между двумя моими столами: Users
и Companies
.
public class User
{
public int CompanyId { get; set; }
public Company Company { get; set; }
}
public class Company
{
public List<User> Users { get; set; }
}
Теперь я должен изменить это на «Многие ко многим». Это моя промежуточная модель
public class CompanyUser
{
public int CompanyId { get; set; }
public Company Company { get; set; }
public string UserId { get; set; }
public User User { get; set; }
}
И мои измененные модели
public class User : IdentityUser
{
public List<CompanyUser> CompanyUsers { get; set; } = new List<CompanyUser>();
}
public class Company
{
public List<CompanyUser> CompanyUsers { get; set; } = new List<CompanyUser>();
}
, но автоматически сгенерированная миграция просто удаляет столбец CompanyId
в моей таблице Users
, и все данные потеря.
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Users_Companies_CompanyId",
table: "Users");
migrationBuilder.DropIndex(
name: "IX_Users_CompanyId",
table: "Users");
migrationBuilder.CreateTable(
name: "CompanyUsers",
columns: table => new
{
CompanyId = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CompanyUsers", x => new { x.CompanyId, x.UserId });
table.ForeignKey(
name: "FK_CompanyUsers_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CompanyUsers_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.DropColumn(
name: "CompanyId",
table: "Users");
migrationBuilder.DropColumn(
name: "IsConfirmedByCompany",
table: "Users");
migrationBuilder.CreateIndex(
name: "IX_CompanyUsers_UserId",
table: "CompanyUsers",
column: "UserId");
}
Я хочу перенести эти данные в CompanyUser
.