После запуска update-database я получил эту ошибку
PM> update-database
Build started...
Build succeeded.
Applying migration '20240403225657_InitialMigration'.
Failed executing DbCommand (44ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Développeurs] (
[ID_Développeur] int NOT NULL IDENTITY,
[Nom_Développeur] nvarchar(max) NOT NULL,
[ID_Projet] int NOT NULL,
[IsM] bit NOT NULL DEFAULT CAST(0 AS bit),
[ID_Planning] int NOT NULL,
CONSTRAINT [PK_Développeurs] PRIMARY KEY ([ID_Développeur]),
CONSTRAINT [FK_Développeurs_Plannings_ID_Planning] FOREIGN KEY ([ID_Planning]) REFERENCES [Plannings] ([ID_Planning]) ON DELETE CASCADE,
CONSTRAINT [FK_Développeurs_Projets_ID_Projet] FOREIGN KEY ([ID_Projet]) REFERENCES [Projets] ([ID_Projet]) ON DELETE CASCADE
);
Microsoft.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN KEY constraint 'FK_Développeurs_Projets_ID_Projet' on table 'Développeurs' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:32566a8f-df7d-4889-9bb2-48bef4f43474
Error Number:1785,State:0,Class:16
Introducing FOREIGN KEY constraint 'FK_Développeurs_Projets_ID_Projet' on table 'Développeurs' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
Я попробовал добавить .OnDelete(DeleteBehavior.NoAction); - ничего не изменилось.
Вот мой код:
Projets.cs:
using System.ComponentModel.DataAnnotations;
namespace Projet.Models
{
public class Projets
{
[Key]
public int ID_Projet { get; set; }
[Required]
public string Nom_Projet { get; set; }
public string Description_Projet { get; set; }
[Required]
public string Version_Projet { get; set; }
[Required]
public string Révision_Projet { get; set; }
[Required]
public string Statut_Projet { get; set; }
public List<Développeurs> Développeurs { get; } = new List<Développeurs>();
public Plannings? Plannings { get; set; }
public ICollection<Environnements> Environnements { get; } = new List<Environnements>();
public List<BDDs> BDDs { get; } = new List<BDDs>();
public ICollection<Languages> Languages { get; } = new List<Languages>();
public List<Sites> Sites { get; } = new List<Sites>();
public List<Toolboxes> Toolboxes { get; } = new List<Toolboxes>();
}
}
Développeurs.cs
using System.ComponentModel.DataAnnotations;
namespace Projet.Models
{
public class Développeurs
{
[Key]
public int ID_Développeur { get; set; }
[Required]
public string Nom_Développeur { get; set; }
public int ID_Projet { get; set; }
public Projets Projet { get; set; } // Navigation property
public bool IsM { get; set; } // Discriminator
public int ID_Planning { get; set; }
public Plannings Plannings { get; set; } = null;
}
}
ProjetContext.cs
//using System.Data.Entity;
using Microsoft.EntityFrameworkCore;
using Projet.Models;
namespace Projet
{
public class ProjetContext : DbContext
{
public ProjetContext()
{
}
public ProjetContext(DbContextOptions options) : base(options)
{
}
public DbSet<BDDs> BDDs { get; set; }
public DbSet<Développeurs> Développeurs { get; set; }
public DbSet<Environnements> Environnements { get; set; }
public DbSet<Languages> Languages { get; set; }
public DbSet<Plannings> Plannings { get; set; }
public DbSet<Projets> Projets { get; set; }
public DbSet<Sites> Sites { get; set; }
public DbSet<Toolboxes> Toolboxes { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=Projet;TrustServerCertificate=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Développeurs>()
.HasOne(d => d.Projet)
.WithMany(p => p.Développeurs)
.HasForeignKey(d => d.ID_Projet)
.IsRequired();
modelBuilder.Entity<Développeurs>()
.Property(d => d.IsM)
.HasDefaultValue(false);
modelBuilder.Entity<Plannings>()
.HasMany(e => e.Développeurs)
.WithOne(e => e.Plannings)
.HasForeignKey(e => e.ID_Planning).IsRequired();
modelBuilder.Entity<Projets>()
.HasOne(e => e.Plannings)
.WithOne(e => e.Projets)
.HasForeignKey<Projets>(e => e.ID_Projet).IsRequired();
modelBuilder.Entity<Projets>()
.HasMany(e => e.Environnements)
.WithOne(e => e.Projets)
.HasForeignKey(e => e.ID_Projet)
.IsRequired();
modelBuilder.Entity<Projets>()
.HasMany(e => e.BDDs)
.WithMany(e => e.Projets)
.UsingEntity<ProjetsBDDs>(
l => l.HasOne<BDDs>().WithMany().HasForeignKey(e => e.ID_BDD),
r => r.HasOne<Projets>().WithMany().HasForeignKey(e => e.ID_Projet));
modelBuilder.Entity<Projets>()
.HasMany(e => e.Languages)
.WithOne(e => e.Projets)
.HasForeignKey(e => e.ID_Projet)
.IsRequired();
modelBuilder.Entity<Projets>()
.HasMany(e => e.Sites)
.WithMany(e => e.Projets)
.UsingEntity<ProjetsSites>(
l => l.HasOne<Sites>().WithMany().HasForeignKey(e => e.ID_Site),
r => r.HasOne<Projets>().WithMany().HasForeignKey(e => e.ID_Projet));
modelBuilder.Entity<Projets>()
.HasMany(e => e.Toolboxes)
.WithMany(e => e.Projets)
.UsingEntity<ProjetsTools>(
l => l.HasOne<Toolboxes>().WithMany().HasForeignKey(e => e.ID_Toolbox),
r => r.HasOne<Projets>().WithMany().HasForeignKey(e => e.ID_Projet));
}
}
}
Migration script
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Projet.Migrations
{
/// <inheritdoc />
public partial class InitialMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Projets",
columns: table => new
{
ID_Projet = table.Column<int>(type: "int", nullable: false),
Nom_Projet = table.Column<string>(type: "nvarchar(max)", nullable: false),
Description_Projet = table.Column<string>(type: "nvarchar(max)", nullable: false),
Version_Projet = table.Column<string>(type: "nvarchar(max)", nullable: false),
Révision_Projet = table.Column<string>(type: "nvarchar(max)", nullable: false),
Statut_Projet = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Projets", x => x.ID_Projet);
table.ForeignKey(
name: "FK_Projets_Plannings_ID_Projet",
column: x => x.ID_Projet,
principalTable: "Plannings",
principalColumn: "ID_Planning",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Développeurs",
columns: table => new
{
ID_Développeur = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nom_Développeur = table.Column<string>(type: "nvarchar(max)", nullable: false),
ID_Projet = table.Column<int>(type: "int", nullable: false),
IsM = table.Column<bool>(type: "bit", nullable: false, defaultValue: false),
ID_Planning = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Développeurs", x => x.ID_Développeur);
table.ForeignKey(
name: "FK_Développeurs_Plannings_ID_Planning",
column: x => x.ID_Planning,
principalTable: "Plannings",
principalColumn: "ID_Planning",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Développeurs_Projets_ID_Projet",
column: x => x.ID_Projet,
principalTable: "Projets",
principalColumn: "ID_Projet",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Développeurs_ID_Projet",
table: "Développeurs",
column: "ID_Projet");
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Projets");
migrationBuilder.DropTable(
name: "Développeurs");
}
}
}
Цените любую помощь.





Из-за ошибки здесь:
Microsoft.Data.SqlClient.SqlException (0x80131904): введение ограничения FOREIGN KEY «FK_Développeurs_Projets_ID_Projet» в таблице «Développeurs» может вызвать циклы или несколько каскадных путей. Укажите ON DELETE NO ACTION или ON UPDATE NO ACTION или измените другие ограничения FOREIGN KEY.
Вам нужно будет указать свойство: «Удалить без действий» или «Обновить без действий». Вы можете сделать это через контекст как таковой:
modelBuilder.Entity<Projets>()
.HasOne(e => e.Plannings)
.WithOne(e => e.Projets)
.OnDelete(/*DELETE BEHAVIOR HERE*/);
Раньше у меня возникала эта проблема при многократном указании отношений свойств. Где вы указали спецификации ondelete и on update?
Я добавил сценарий миграции, если вы хотите его проверить.
Я указал это в 'modelBuilder.Entity<Développeurs>().HasOne(d => d.Projet).WithMany(p => p.Développeurs).HasForeignKey(d => d.ID_Projet).IsRequired()..OnDelete (DeleteBehavior.NoAction);' Но ничего не изменилось и я удалил его.
Вы удалили предыдущую миграцию и создали ее заново?
Нет. Миграция была автоматически создана EF.Core.
Решение состоит в том, чтобы указать свойство в скрипте миграции:
table.ForeignKey(
name: "FK_Développeurs_Projets_ID_Projet",
column: x => x.ID_Projet,
principalTable: "Projets",
principalColumn: "ID_Projet",
onDelete: ReferentialAction.NoAction);
а затем введите команду update-database в 'PACKAGE MANAGER CONSOLE'
Я все еще получаю ту же ошибку даже после указания свойств.