title: EF Core 5 One-to-many relationship problem
body: <p>In this example a user has zero or many bills, one bill can be assigned to one user. Bill can also be created but never assigned.</p>
  <pre><code>public class User
  {
    public int Id{ get; set; }   
    public List&lt;Bill&gt; bills{ get; set; }
  }
          
  public class Bill
  {
    public int Id { get; set; }
          
    public int userId{ get; set; }
    public User user{ get; set; }
  }
  </code></pre>
  <p>I've also added this in my DB context configuration:</p>
  <pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
   modelBuilder.Entity&lt;Bill&gt;()
               .HasOne(b =&gt; b.user)
               .WithMany(u =&gt; u.bills)
               .HasForeignKey(b =&gt; b.userId);
  }
  </code></pre>
  <p>I've realized it through a unit of work + repository pattern. In my <code>BillService.cs</code> I would like to have a method that allows me to update/add a bill and assign it to a user.</p>
  <p>If the user doesn't exist in DB it should add it. If the user exists it should update it.</p>
  <p>I've tried two approaches.
  First:</p>
  <pre><code>public async Task&lt;void&gt; AddUpdateBill(AddBillModel model){
      Bill bill= await unitOfWork.BillRepository.GetByID(model.billId);
      
      if( unitOfWork.UserRepo.GetById(model.userId) == null){
          unitOfWork.UserRepo.Insert(model.user);
      }else{
          unitOfWork.UserRepo.Update(model.user);
      }
      bill.user = model.user;
      unitOfWork.BillRepository.Update(bill);
      unitOfWork.Save();
  }
  </code></pre>
  <p>Second:</p>
  <pre><code>public async Task&lt;void&gt; AddUpdateBill(AddBillModel model)
  {
      Bill bill= await unitOfWork.BillRepository.GetByID(model.billId);
      bill.user = model.user;
      unitOfWork.BillRepository.Update(bill);
      unitOfWork.Save();
  }
  </code></pre>
  <p>In both cases, I've got the problem of duplicated primary-key or entity already tracked.</p>
  <p>Which is the best approach or the right way to do it?</p>
  <p>EDIT: Sorry, BillRepo and BillRepository are the same class.</p>
  <pre><code>public async Task&lt;Bill&gt; GetByID(int id)
  {
     return await context
             .bill
             .Include(b =&gt; b.user)
             .Where(b=&gt; b.id == id)
             .FirstOrDefaultAsync();
  }
  
  public void Update(Bill bill)
  {
     context.Entry(bill).CurrentValues.SetValues(bill);
  }
  </code></pre>