更新数据库失败

问题描述 投票:0回答:1

运行后

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));
 }

    }


}

感谢任何帮助。

c# database entity-framework-core
1个回答
0
投票

由于这里的错误:

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.

您必须将该属性指定为“删除时不执行任何操作”或“更新时不执行任何操作”。您可以通过上下文来做到这一点:

    modelBuilder.Entity<Projets>()
    .HasOne(e => e.Plannings)
    .WithOne(e => e.Projets)
    .OnDelete(/*DELETE BEHAVIOR HERE*/); 
© www.soinside.com 2019 - 2024. All rights reserved.