locked
Two ForeignKey to define in the same table RRS feed

  • Question

  •     using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
        public class CustomerBase
        {
            public CustomerBase()
            {
                this.Payments = new List<PaymentBase>();
                this.Documents = new List<DocumentBase>();
                this.OwnerShips = new List<OwnerShipBase>();
            }
            [Key]
            public Int64 MusteriId { get; set; }
            public string KimlikNo { get; set; }
            public string Unvan { get; set; }
            public byte[] MusteriResim { get; set; }
            public virtual ICollection<OwnerShipBase> OwnerShips { get; set; }
            public virtual ICollection<PaymentBase> Payments { get; set; }
            public virtual ICollection<DocumentBase> Documents { get; set; }
        }

    and

        using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
        public class OwnerShipBase
        {
            public OwnerShipBase()
            {
               this.Payments = new List<PaymentBase>();
               this.Documents = new List<DocumentBase>();
            }
            [Key]
            public Int64 IsId { get; set; }
            //******************************************************
            public Int64 MusteriId { get; set; }
            [ForeignKey("MusteriId")]
            public virtual CustomerBase CustomerBase { get; set; }
            //******************************************************
            public DateTime? Tarih { get; set; }
            public string Acıklama { get; set; }
            public virtual ICollection<PaymentBase> Payments { get; set; }
            public virtual ICollection<DocumentBase> Documents { get; set; }
          }

    and

        using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
        public class PaymentBase
        {
            [Key]
            public Int64 OdemeId { get; set; }
           //********************************************************
            public Int64 MusteriId { get; set; }
            [ForeignKey("MusteriId")]
            public virtual CustomerBase CustomerBase { get; set; }
            public Int64 IsId { get; set; }
            [ForeignKey("IsId")]
            public virtual OwnerShipBase OwnerShipBase { get; set; }
            //********************************************************
            public DateTime? Tarih { get; set; }
            public Decimal? Nakit { get; set; }
    
        }

    and

        using System;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
        public class DocumentBase
        {
            [Key]
            public Int64 DosyaId { get; set; }
            //********************************************************
            public Int64 MusteriId { get; set; }
            [ForeignKey("MusteriId")]
            public virtual CustomerBase CustomerBase { get; set; }
            public Int64 IsId { get; set; }
            [ForeignKey("IsId")]
            public virtual OwnerShipBase OwnerShipBase { get; set; }
            //********************************************************
            public string DosyaAdi { get; set; }
            public byte[] DosyaBinary { get; set; }
        }

    and

        using EntityModels;
        using System.Data.Entity;
        public class DataContext:DbContext
        {
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
               
            }
            public DbSet<CustomerBase> CustomerBases { get; set; }
            public DbSet<OwnerShipBase> OwnerShipBases { get; set; }
            public DbSet<PaymentBase> PaymentBases { get; set; }
            public DbSet<DocumentBase> DocumentBases { get; set; }
          
        }

    And

           public static bool InsertCustomer(CustomerBase Kaydet)
            {
                using (var db = new DataContext())
                {
    
    
                    db.CustomerBases.Add(Kaydet);
                   return( db.SaveChanges() > 0);
                }
            }

    error;

    System.Data.SqlClient.SqlException was unhandled by user code
      HResult=-2146232060
      Message=Introducing FOREIGN KEY constraint 'FK_dbo.OwnerShipBases_dbo.CustomerBases_MusteriId' on table 'OwnerShipBases' 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.
      Source=.Net SqlClient Data Provider
      ErrorCode=-2146232060
      Class=16
      LineNumber=1
      Number=1785
      Procedure=""
      Server=.\SQLEXPRESS
      State=0
      StackTrace:
           konum: System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
           konum: System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
           konum: System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
           konum: System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
           konum: System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
           konum: System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
           konum: System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
           konum: System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
           konum: System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
           konum: System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
           konum: System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
           konum: System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
           konum: System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
           konum: System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
           konum: System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
           konum: System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
           konum: System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
           konum: System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
           konum: System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
           konum: System.Data.Entity.Migrations.Infrastructure.MigratorBase.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
           konum: System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
           konum: System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
           konum: System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
           konum: System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
           konum: System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
           konum: System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
           konum: System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
           konum: System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update()
           konum: System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
           konum: System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
           konum: System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
           konum: System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
           konum: System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
           konum: System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
           konum: System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
           konum: System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
           konum: System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
           konum: System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
           konum: System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
           konum: System.Data.Entity.Internal.InternalContext.Initialize()
           konum: System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
           konum: System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
           konum: System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
           konum: System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
           konum: System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
           konum: System.Data.Entity.DbSet`1.Add(TEntity entity)
           konum: CCTrackingBase.EntityQueries.Customer.InsertCustomer(CustomerBase Kaydet) e:\Data_Backup\Özel_Programlarım\Kenan YILMAZ\CCTrackingDesktop\CCTrackingBase\EntityQueries\Customer.cs içinde: satır 16
           konum: CCTrackingDesktop.MainWindow.Ekle() e:\Data_Backup\Özel_Programlarım\Kenan YILMAZ\CCTrackingDesktop\CCTrackingDesktop\AnaPanel.xaml.cs içinde: satır 47
           konum: CCTrackingDesktop.MainWindow..ctor() e:\Data_Backup\Özel_Programlarım\Kenan YILMAZ\CCTrackingDesktop\CCTrackingDesktop\AnaPanel.xaml.cs içinde: satır 20
      InnerException: 

    I want to make ForeignKey IsId and  musteriId areas but I did not succeed;Thanks for your help



    Monday, April 27, 2015 7:50 PM

Answers

  • Hello Kenan,

    >>I want to make ForeignKey IsId and  musteriId areas but I did not succeed;

    With your provided model, I made a test with and reproduced this issue and this issue is caused by a cause cycles or multiple cascade paths, the exception message also mentions and it actually provided the workaround which Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. In the OnModelCreating method of your context class, adding code as below:

    modelBuilder.Entity<PaymentBase>().HasRequired(p => p.CustomerBase).WithMany().WillCascadeOnDelete(false);
    
                modelBuilder.Entity<PaymentBase>().HasRequired(p => p.OwnerShipBase).WithMany().WillCascadeOnDelete(false);
    
                modelBuilder.Entity<DocumentBase>().HasRequired(p => p.CustomerBase).WithMany().WillCascadeOnDelete(false);
    
                modelBuilder.Entity<DocumentBase>().HasRequired(p => p.OwnerShipBase).WithMany().WillCascadeOnDelete(false);
    

    On my side, the model generates the database successfully.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Kenan YILMAZ Wednesday, April 29, 2015 6:26 AM
    Wednesday, April 29, 2015 2:37 AM

All replies

  • Hello Kenan,

    >>I want to make ForeignKey IsId and  musteriId areas but I did not succeed;

    With your provided model, I made a test with and reproduced this issue and this issue is caused by a cause cycles or multiple cascade paths, the exception message also mentions and it actually provided the workaround which Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. In the OnModelCreating method of your context class, adding code as below:

    modelBuilder.Entity<PaymentBase>().HasRequired(p => p.CustomerBase).WithMany().WillCascadeOnDelete(false);
    
                modelBuilder.Entity<PaymentBase>().HasRequired(p => p.OwnerShipBase).WithMany().WillCascadeOnDelete(false);
    
                modelBuilder.Entity<DocumentBase>().HasRequired(p => p.CustomerBase).WithMany().WillCascadeOnDelete(false);
    
                modelBuilder.Entity<DocumentBase>().HasRequired(p => p.OwnerShipBase).WithMany().WillCascadeOnDelete(false);
    

    On my side, the model generates the database successfully.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Kenan YILMAZ Wednesday, April 29, 2015 6:26 AM
    Wednesday, April 29, 2015 2:37 AM
  • Hi Fred;
    Thank you so much for your answer 
    but I solved the problem in the following way;

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Add(new FKConvention());
                base.OnModelCreating(modelBuilder);
            }

    and;

     public class FKConvention : IConceptualModelConvention<AssociationType>
        {
    
            public void Apply(AssociationType item, DbModel model)
            {
                if (item.IsForeignKey)
                {
                    item.Constraint.FromRole.DeleteBehavior = OperationAction.None;
                    item.Constraint.ToRole.DeleteBehavior = OperationAction.None;
                }
            }
        }
    Regards;

    Wednesday, April 29, 2015 6:25 AM