title: Which is the best practice to add a related objects in Entity Framework?
body: <p>I recently created a Web API project in .NET Core 3.1 and I implemented Entity Framework Core using <em>code first</em> approach. Each of my models refer to others like this:</p>
  <pre><code>public class Condominium
  {
      public int Id { get; set; }
      public Address Address { get; set; }
      public int Levels { get; set; }
      public string Description { get; set; }
      public CondominiumType CondominiumType { get; set; }
  }
  </code></pre>
  <p>As you can see in this example I am referring to Address and to CondominiumType without using reference Id. Entity Framework will create the corresponding foreign keys when the database will be migrated.</p>
  <p>This works perfectly fine when I have to add a new Condominium with a new Address but i am facing an issue when I want to add an <strong>existing</strong> Address or Condominium Type.</p>
  <p>When I pass an object to the context with an Id that has already been added to the database the program throws an exception because i'm violating the UNIQUE constraint of the table. I know that I can fix this problem by adding reference keys writing something like this</p>
  <pre><code>    public class Condominium
  {
      public int Id { get; set; }
      public int AddressId { get; set; }
      public Address Address { get; set; }
      public int Levels { get; set; }
      public string Description { get; set; }
      public int CondominiumTypeId { get; set; }
      public CondominiumType CondominiumType { get; set; }
  
  }
  </code></pre>
  <p>BUT I'm wondering which will be the proper way to resolve cases like this. <strong>¿Is It Possible to add existing objects without rewriting my classes?</strong></p>
  <p>In the business Layer i'm passing the data throw an UnitOfWork Patter:</p>
  <pre><code> public async Task&lt;bool&gt; AddCondominium(int AgencyId,CondominiumDTO newCondominium)
      {
          var condominium = _mapper.Map&lt;Condominium&gt;(newCondominium);
          condominium.ConsortiumAdministrationAgency = new ConsortiumAdministrationAgency() { Id = AgencyId };
          _unitOfWork.Addresses.Add(condominium.Address);
          _unitOfWork.Condominiums.Add(condominium);
          return await _unitOfWork.CompleteAsync();
      }
  </code></pre>