title: Add/insert a new entry containing complex type in Entity Framework 7 Code first
body: <p>I am trying to add a new entry for my object model which has few complex type, using EF 7 code first. But it's not working and throwing exception.</p>
  
  <p>Model:</p>
  
  <pre><code>public class Student 
  {
    public int id {get; set;}
    public string Name {get; set;}
    public Address Address {get; set;} -&gt; complex type
  }
  
  public class Address 
  {
    public int Id {get;set;}
    public string Location {get;set;}
  }
  </code></pre>
  
  <p>Code first code:</p>
  
  <pre><code>class SchoolContext {
  DbSet&lt;Student&gt; Students {get; set;}
  DbSet&lt;Address&gt; Addresses {get; set;}
  
  }
  
  var context = new SchoolContext();
  
  context.Students.Add(new Student { Id = 1, Name = "XYZ", Address = new Address { Id = 2, Location = "US" } } -&gt; The add method has second parameter which says include dependent objects, and by default it is true.
  
  context.SaveChanges();
  </code></pre>
  
  <p>This throws exception:</p>
  
  <blockquote>
    <p>{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Student_Address_AddressId\". The conflict occurred in database \"School\", table \"dbo.Address\", column 'Id'.\r\nThe statement has been terminated."}</p>
  </blockquote>
  
  <p>This error I think means, the Address object does not exists in database, and if I add the address first and then Student, it works. But this is just too much code, as in my real application objects has many complex types.</p>
  
  <p>Ideally this should work, but it does not.</p>