This project has moved and is read-only. For the latest updates, please go here.

Foreign Key reference error while creating a child entity after creating a parent entity in the same test

Nov 6, 2014 at 6:58 PM
Definitely enjoying "Effort", however, I am stuck at a problem.

I have a test where I create a parent entity and then create a child entity based on the ID of the parent entity. This works fine using the real database.

This is what the code looks like (obviously, the code isn't complete).
        public async Task CreateStudentTest()
            // SUCCESS
            var schoolResult = await _schoolHelper.Create();
            Assert.True(schoolResult.Success, schoolResult.Message); 

           // Success: Verified the newly created ID and the entity is there
            var school = await _schoolHelper.Get<School>(schoolResult.CreatedId);

            var studentEntity = _helper.GenerateStudentTest(DateTime.UtcNow, schoolResult.CreatedId);

            // Throws the error here because when creating the "studentEntity" it cannot find the college entity that was created/verified previously
            var result = await _studentLogic.AddOrUpdateStudent(studentEntity);
The exact error I am getting is: {"Foreign key violation [Students :: SchoolId]. The key value [2] does not exists in the referenced table [Schools :: Id].. Error code: RelationError"}

Any help would be highly appreciated.
Nov 6, 2014 at 8:51 PM
The question was asked a little too fast without much research. The answer is using to use the CreatePersistent method of DbConnectionFactory.

I found the answer in this article.

And it works like Magic! Thank you Effort and everyone supporting it!
Marked as answer by Khadga on 11/6/2014 at 12:51 PM
Nov 13, 2014 at 9:14 PM

Good to see you solved the problem on your own.

Using persistent fake connection objects is an easy and convenient way to share the same database across different points of your application. However I would strongly advice to design an architecture were you can reuse the same transient connection object at these points. See my blog post to get some idea.