Base solution for your next web application
BLACK FRIDAY
From Nov 21
To Dec 1
XXDAYS : XXHRS : XXMIN : XXSEC
SAVE UP TO$3K
Also valid for the
existing customers!
Open Closed

System.Data.Entity.Infrastructure.DbUpdateException #641


0
nipunjoshi created

I have written my first test case.But unfortunately it gives below mentioned exception :cry: Could you tell me why ? Thanks.

Test case :

public class AcquisitionTypeAppServiceTests : AppTestBase
    {
        private readonly IAcquisitionTypeAppService _acquisitionTypeAppService;

        public AcquisitionTypeAppServiceTests()
        {
            _acquisitionTypeAppService = Resolve<IAcquisitionTypeAppService>();
        }

        [Fact]
        public async Task Test_GetAllAcquisitionTypesAsync()
        {
            //Act
            var acquisitionTypes = await _acquisitionTypeAppService.GetAllAcquisitionTypesAsync();

            //Assert
            acquisitionTypes.Items.Count.ShouldBe(5);
        }


    }

Exception :

Test Name:	IP.Tests.AcquisitionTypes.AcquisitionTypeAppServiceTests.Test_GetAllAcquisitionTypesAsync
Test FullName:	 IP.Tests.AcquisitionTypes.AcquisitionTypeAppServiceTests.Test_GetAllAcquisitionTypesAsync
Test Source:	\Tests\IP.Tests\AcquisitionTypes\AcquisitionTypeAppServiceTests.cs : line 19
Test Outcome:	Failed
Test Duration:	0:00:00.001

Result Message:	
System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- System.Data.Entity.Core.UpdateException : An error occurred while updating the entries. See the inner exception for details.
-------- System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
------------ NMemory.Exceptions.ForeignKeyViolationException : Foreign key violation [IpProperties :: CountyId]. The key value [3] does not exists in the referenced table [IpCounties :: Id].. Error code: RelationError
Result StackTrace:	
at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at Abp.EntityFramework.AbpDbContext.SaveChanges()
   at Joshi.IP.Migrations.Seed.InitialPropertiesCreator.Create() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.EntityFramework\Migrations\Seed\InitialPropertiesCreator.cs:line 111
   at Joshi.IP.Migrations.Seed.InitialDbBuilder.Create() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.EntityFramework\Migrations\Seed\InitialDbBuilder.cs:line 22
   at Joshi.IP.Tests.AppTestBase.<.ctor>b__0(IpDbContext context) in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AppTestBase.cs:line 36
   at Joshi.IP.Tests.AppTestBase.UsingDbContext(Action`1 action) in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AppTestBase.cs:line 70
   at Joshi.IP.Tests.AppTestBase..ctor() in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AppTestBase.cs:line 34
   at Joshi.IP.Tests.AcquisitionTypes.AcquisitionTypeAppServiceTests..ctor() in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AcquisitionTypes\AcquisitionTypeAppServiceTests.cs:line 12
----- Inner Stack Trace -----
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.&lt;Update&gt;b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.&lt;&gt;c__DisplayClass2a.&lt;SaveChangesInternal&gt;b__27()
   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
----- Inner Stack Trace -----
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Effort.Internal.Common.DatabaseReflectionHelper.InsertEntity(ITable table, Object entity, Transaction transaction)
   at Effort.Internal.CommandActions.InsertCommandAction.CreateAndInsertEntity(ITable table, IList`1 memberBindings, Transaction transaction)
   at Effort.Internal.CommandActions.InsertCommandAction.ExecuteDataReader(ActionContext context)
   at Effort.Provider.EffortEntityCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;Reader&gt;b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
----- Inner Stack Trace -----
   at NMemory.Tables.Relation`4.ValidateEntityCore(TForeign foreign)
   at NMemory.Tables.Relation`4.NMemory.Tables.IRelationInternal.ValidateEntity(Object foreign)
   at NMemory.Execution.ExecutionHelper.ValidateForeignKeys(IList`1 relations, IEnumerable`1 referringEntities)
   at NMemory.Execution.CommandExecutor.ExecuteInsert[T](T entity, IExecutionContext context)
   at NMemory.Tables.DefaultTable`2.InsertCore(TEntity entity, Transaction transaction)
   at Effort.Internal.DbManagement.Engine.ExtendedTable`2.InsertCore(TEntity entity, Transaction transaction)
   at NMemory.Tables.Table`2.Insert(TEntity entity, Transaction transaction)
   at Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.InsertEntity[TEntity](ITable`1 table, TEntity entity, Transaction transaction)

10 Answer(s)
  • 0
    hikalkan created
    Support Team

    Hi,

    Actually, it says the reason: "Foreign key violation [IpProperties :: CountyId]. The key value [3] does not exists in the referenced table [IpCounties :: Id].." Have you checked it?

  • 0
    nipunjoshi created

    Hi, Actually those values are there. Really strange.What could be the other reason for this ? Please see the images.

  • 0
    hikalkan created
    Support Team

    Unit tests does not run in the real database. It works in-memory database. So, probably this data does not exists in your initial test data.

  • 0
    nipunjoshi created

    It's there on the seed data also. Then why's that ? Please see that below. Thanks.

    Note : the exception happens here in the below class : _context.SaveChanges();

    InitialPropertiesCreator.cs

    public class InitialPropertiesCreator
        {
            private readonly IpDbContext _context;
    
            public InitialPropertiesCreator(IpDbContext context)
            {
                _context = context;
            }
    
            public void Create()
            {
                var dist1 = _context.Properties.FirstOrDefault(p => p.Dist == "dist1");
                if (dist1 == null)
                {
                    _context.Properties.Add(
                        new Property
                        {
                            IsVacant = true,
                            IsPropertyToConsider = false,
                            Dist = "dist1",
                            Sec = "sec1",
                            Blk = "blk1",
                            Lot = "lot1",
                            Lot2 = "lot2",
                            Mls = "mls1",
                            Priority = "priority1",
                            Tfmv = "Tfmv1",
                            Fmv = "Fmv1",
                            Construction = "Construction1",
                            Bid = "Bid1",
                            ListingPrice = 12.25m,
                            Contact = "Contact1",
                            DeedDate = DateTime.UtcNow,
                            TransferTax = 12.9m,
                            OriginalPurchasePrice = 45.6m,
                            Taxes = 85.3m,
                            TotalValuation = 41.2m,
                            Ev = 47.3m,
                            BuyBackAmount = 50.2m,
                            CountyId = 3,
                            PropertyClassId = 1,
                            SchoolDistrictId = 1,
                            StatusId = 1,
                            Address = new Address
                            {
                                StreetName = "1st Street",
                                StreetNumber = "1581",
                                CityId = 1,
                                StateId = 1,
                            },
                            PurchasedById = 1,
                            ShowId = 1,
                            CodeId = 1,
    
                        });
                }
    
                var dist2 = _context.Properties.FirstOrDefault(p => p.Dist == "dist2");
                if (dist2 == null)
                {
                    _context.Properties.Add(
                        new Property
                        {
                            IsVacant = true,
                            IsPropertyToConsider = false,
                            Dist = "dist2",
                            Sec = "sec2",
                            Blk = "blk2",
                            Lot = "lot2",
                            Lot2 = "lot3",
                            Mls = "mls2",
                            Priority = "priority2",
                            Tfmv = "Tfmv2",
                            Fmv = "Fmv2",
                            Construction = "Construction2",
                            Bid = "Bid2",
                            ListingPrice = 12.25m,
                            Contact = "Contact2",
                            DeedDate = DateTime.UtcNow,
                            TransferTax = 12.9m,
                            OriginalPurchasePrice = 45.6m,
                            Taxes = 85.3m,
                            TotalValuation = 41.2m,
                            Ev = 47.3m,
                            BuyBackAmount = 50.2m,
                            CountyId = 4,
                            PropertyClassId = 2,
                            SchoolDistrictId = 2,
                            StatusId = 2,
                            Address = new Address
                            {
                                StreetName = "2nd Street",
                                StreetNumber = "1582",
                                CityId = 2,
                                StateId = 2,
                            },
                            PurchasedById = 2,
                            ShowId = 2,
                            CodeId = 2,
                        });
                }
    
                _context.SaveChanges(); // it gives the exception here
            }
        }
    

    InitialCountiesCreator.cs

    public class InitialCountiesCreator
        {
            private readonly IpDbContext _context;
    
            public InitialCountiesCreator(IpDbContext context)
            {
                _context = context;
            }
    
            public void Create()
            {
                var county1 = _context.Counties.FirstOrDefault(p => p.Name == "Orange");
                if (county1 == null)
                {
                    _context.Counties.Add(
                        new County
                        {
                            Name = "Orange",
                            State = "NY",
                        });
                }
    
                var county2 = _context.Counties.FirstOrDefault(p => p.Name == "Ulster");
                if (county2 == null)
                {
                    _context.Counties.Add(
                       new County
                       {
                           Name = "Ulster",
                           State = "NY",
                       });
                }
            }
        }
    
  • 0
    nipunjoshi created

    Other issue is according to the above exception where it checks the data on the tables also no (i.e "IpProperties" and "IpCounties" are my physical tables) ? Am I right ? Here it is :

    NMemory.Exceptions.ForeignKeyViolationException : Foreign key violation [IpProperties :: CountyId]. The key value [3] does not exists in the referenced table [IpCounties :: Id]..
    
  • 0
    hikalkan created
    Support Team

    There is only 2 Country in your seed data (InitialCountiesCreator.cs) but you are trying to set CountryId = 3. So, there is no country with CountryId = 3.

  • 0
    sampath created

    Yes,You're right.I have done as above where I removed some bad data on the above tables and after that I didn't Reseed the PK values.It is working fine with the real db.But not working with the Fake db.But when I changed it back to 1 and 2 then it works.Thanks.

  • 0
    sampath created

    Hi, Is there any way to explore the data on fake db ? Any tool or like that ? Thanks.

  • 0
    hikalkan created
    Support Team

    I don't know, since it's dynamic and in-memory. But, trying to investigate a unit test manually may not be a good practice.

    Also, I don't suggest to write hard-coded Id values. Why don't you just query it when you need? Thus, you can check if it's exists.

  • 0
    sampath created

    Thanks a lot.Sure I'll follow those guidance :)