Base solution for your next web application
Open Closed

Insert into Many to Many tables. #7008


User avatar
0
defacto created

DevelopmentObjectiveCategoryMapping ia a many-to-many table. When we insert 3 entities into it we only see that only the latest one is inserted. Do you have any idea why this could be happening?

public async Task CreateObjective(CreateDevelopmentObjectiveInput input)
{
     var o1 = new DevelopmentObjective
     {
         FormId = input.FormId,
         TemplateId = input.TemplateId,
         MeasureOfSuccess = input.MeasureOfSuccess,
         CompletionDate = input.CompletionDate,
         Status = input.Status
     };
    
     await _objectiveRepository.InsertAndGetIdAsync(o1);

     var docm1 = new DevelopmentObjectiveCategoryMapping
     {
         ObjectiveId = o1.Id,
         CategoryId = input.ObjectiveCategory.CategoryId,
         OtherCategoryName = input.ObjectiveCategory.OtherCategoryName,
         CategoryDescription = input.ObjectiveCategory.CategoryDescription
     };

     var docm2 = new DevelopmentObjectiveCategoryMapping
     {
         ObjectiveId = o1.Id,
         CategoryId = input.ObjectiveCategory.CategoryId,
         OtherCategoryName = input.ObjectiveCategory.OtherCategoryName,
         CategoryDescription = input.ObjectiveCategory.CategoryDescription
     };

     var docm3 = new DevelopmentObjectiveCategoryMapping
     {
         ObjectiveId = o1.Id,
         CategoryId = input.ObjectiveCategory.CategoryId,
         OtherCategoryName = input.ObjectiveCategory.OtherCategoryName,
         CategoryDescription = input.ObjectiveCategory.CategoryDescription
     };

     await _objectiveCategoryMappingRepository.InsertAndGetIdAsync(docm1);
     await _objectiveCategoryMappingRepository.InsertAndGetIdAsync(docm2);
     await _objectiveCategoryMappingRepository.InsertAndGetIdAsync(docm3);
}

1 Answer(s)
  • User Avatar
    0
    defacto created

    Sorry it was our mistake. I saw that in DbContextModelSnapshot, ObjectiveId of DevelopmentObjectiveCategoryMapping is described as Unique like b.HasIndex("ObjectiveId").IsUnique().