Click here to Skip to main content
15,072,433 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have problem with many-to-many relationship. ive implemented GenericRepository and UnitOfWork pattern.

i have 2 entities, Test and Question

the problem is that when i call these 2 entities from database and want to link them in link table ef is duplicating then in their respective tables. I believe this could be solved with using(var context = new MyDbContext()) statement and linking them inside that using statement but unfortunately UnitOfWork dont allow that, so ive tried using (var scope = new TransactionScope()) with no luck.

for example: i have 5 questions in database and 3 answers for each question and after user is done with test i figure out user score and insert new test row with some data. link table is here to show what questions did user had for that test. when i save test entity every single question and answer is duplicated to database.

public int SaveTestResult(TestEntity testEntity)
        using (var scope = new TransactionScope() )

            testEntity.Questions = testEntity.Questions.OrderBy(q => q.Id).ToList();
            var idlist = testEntity.Questions.Select(x => x.Id).ToList(); // get ids from list of questions from testentity

            //note:i believe this line is causing that behaviour 
            var questionss = _unitOfWork.QuestionRepository.GetMany(q => idlist.Contains(q.Id)).OrderBy(q => q.Id).ToList();//get questions from ids and sort them by id  
            var questions = AutoMapper.Mapper.Map<List<Question>, List<QuestionEntity>>(questionss); //map from Question from db to QuestionEntity
            testEntity.Questions = testEntity.Questions.OrderBy(q => q.Id).ToList();//sort testEtities questions id to match questions above
            var number= 0;
            for (int i = 0; i < testEntity.Questions.Count; i++)
                for (int j = 0; j < testEntity.Questions[i].Answers.Count; j++)
                    if ((testEntity.Questions[i].Answers[j].IsTrueUserChoice == questions[i].Answers[j].IsTrue) && (questions[i].Answers[j].IsTrue == true))

            testEntity.TestScore = number;
            testEntity.Questions = questions;//ading questions from db so model validation would pass. quesiton from testEntiy are not valid, some properties are missing
            var testDb = new Test();
            testDb.TestTime = (testDb.TestDateEnd - testEntity.TestDateStart).Value;
            testDb.TestDateStart = testEntity.TestDateStart.Value;
            testDb.TestScore = testEntity.TestScore;
            testDb.UserId = testEntity.UserId;
            testDb.Questions = AutoMapper.Mapper.Map<List<QuestionEntity>, List<Question>>(testEntity.Questions);
            return number;

note: dont get caught up in logic ive implemented :) focus on problem thanks

What I have tried:

every solution on stackoverflow
Updated 21-Jun-18 12:31pm
F-ES Sitecore 22-Jun-18 4:46am
Not sure I really follow the question, but this usually happens when you create a new entity but don't attach it to the dbcontext and let EF know that the entity already exists, so when you update the context EF thinks it is new and creates it. So you are probably creating new instances of your Question entity (via the AutoMapper?) without telling EF those entities reflect existing entities and are not new ones.

Have a read about attaching entities to the context here
StefanIvovic 22-Jun-18 6:38am
right, u are correct. i know that i am doing just that. but how can i attach tracked entity with repository and UnitOfWork pattern. as u can see in the code i dont have classic dbcontext i have unitOfWork

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900