jhipster / jhipster-dotnetcore

JHipster.NET blueprint
Apache License 2.0
311 stars 91 forks source link

Issue related many-to-many relationship #976

Closed 123445666 closed 2 years ago

123445666 commented 2 years ago

Hi @nicolas63 ,

Overview of the issue

When working with Dao issue, i found a bug related many-to-many relationship with ef.

Motivation for or Use Case

Create or edit a Job History and Save. It shows : 'UNIQUE constraint failed: JobChores.ChoresId, JobChores.JobsId'."

Reproduce the error

I used the app.jdl in the test folder but commented the dto line.

Related issues
Suggest a Fix

My solution is: I'll change this function AddOrUpdateGraph like below.

public void AddOrUpdateGraph<TEntiy>(TEntiy entity, List<string> entitiesToBeUpdated = null) where TEntiy : class
{
          var rootTypeEntity = entity.GetType().Name;
         _context.ChangeTracker.TrackGraph(entity, e =>
          {
              string navigationPropertyName = e.Entry.Entity.GetType().Name;

              var alreadyTrackedEntity = _context.ChangeTracker.Entries().FirstOrDefault(entry => entry.Entity.Equals(e.Entry.Entity));

              if (alreadyTrackedEntity != null)
              {
                  alreadyTrackedEntity.State = EntityState.Detached;
              }
              if (navigationPropertyName != rootTypeEntity && !(entitiesToBeUpdated != null && entitiesToBeUpdated.Contains(navigationPropertyName)))
              {
                  e.Entry.State = EntityState.Unchanged;
              }
              else if (e.Entry.IsKeySet)
              {
                  e.Entry.State = EntityState.Modified;
              }
              else
              {
                  e.Entry.State = EntityState.Added;
              }
          });
}

Do you think it's ok ? If ok, i'll make the pull request. Thank you.

JHipster Version(s)
JHipster configuration
Entity configuration(s) entityName.json files generated in the .jhipster directory
Browsers and Operating System
nicolas63 commented 2 years ago

Yes i think is good, @ivanmonteiro are you also agree ? @123445666 What do you pass in parameter entitiesToBeUpdated ?

123445666 commented 2 years ago

@nicolas63 With the new AddOrUpdateGraph, it'll only update the root Entity (without the child) except "many-to-many relation"

If there are "many-to-many", it'll pass the name of child entity like this List<string> entitiesToBeUpdated = new List<string> { "PieceOfWork" }; return await base.CreateOrUpdateAsync(job, entitiesToBeUpdated);

nicolas63 commented 2 years ago

Maybe it's better to pass a type like List { typeof(PieceOfWork) }; return await base.CreateOrUpdateAsync(job, entitiesToBeUpdated);

Are you ok with this ?

123445666 commented 2 years ago

It's ok, i'll do it that way.

ivanmonteiro commented 2 years ago

Yes i think is good, @ivanmonteiro are you also agree ? @123445666 What do you pass in parameter entitiesToBeUpdated ?

I agree, for the moment we can try @123445666's approach.