title: How can you add a navigation property on a view in EF 6.1 CodeFirst
body: <p>Let's make a case to explain my problem. </p>
  
  <hr>
  
  <p><strong>MyTable1</strong></p>
  
  <p>+id</p>
  
  <p>+myTable2Id</p>
  
  <hr>
  
  <p><strong>MyTable2</strong></p>
  
  <p>+id</p>
  
  <hr>
  
  <p><strong>MyView1</strong></p>
  
  <p>+id</p>
  
  <p>+myTable2Id</p>
  
  <hr>
  
  <p>MyView1 exists in the case, from data from the MyTable1. Now i want to create a Navigation property from my EF6.1 Code first approach in my View to MyTable2. </p>
  
  <p>I know that it was possible from the database first approach, but is it also possible from the code-first approach and how?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I search some on internet, but due many meanings of the word View, it's very hard to find information on it. </p>
  
  <p>Also with the approaches in codes that i tried, i always get an error that the migration can't be completed. Because the Migration tries to add an foreign key to the view, which isn't possible.</p>
  
  <p><strong>EDIT2:</strong> </p>
  
  <p>To elaborate a bit more on my explanation. I want to be able to approach it in code the following way: </p>
  
  <pre><code>Guid table2Id = context.MyView1.FirstOrDefault().MyTable2.id;
  </code></pre>
  
  <p><strong>EDIT3:</strong></p>
  
  <p>I will eleborate a bit more, to see if i can get my problem better explained. </p>
  
  <p>When i added the following to my view Entity: </p>
  
  <pre><code>public virtual MyTable2 Table2 { get; set;}
  </code></pre>
  
  <p>EF will automaticly generate the following migration: </p>
  
  <pre><code>public override void Up() {
      CreateIndex("MyView1", "MyTable2Id");
      AddForeignKey("MyView1", "MyTable2Id", "MyTable2", "id")
  }
  </code></pre>
  
  <p>Which on running update-database gives the following error :</p>
  
  <p>"Cannot create index on view 'MyView1' because the view is not schema bound"</p>
  
  <p>EDIT4: </p>
  
  <p>With help of the comment that the migration aren't of stone.. and are changeable i made it. </p>
  
  <p>I used the following fluentAPI:</p>
  
  <pre><code>    // Map one-to-zero or one relationship 
      modelBuilder.Entity&lt;MyTable2&gt;()
          .HasRequired(t =&gt; t.MyTable1)
          .WithOptional(t =&gt; t.MyTable2);
  
      modelBuilder.Entity&lt;MyTable1&gt;()
          .HasOptional(t =&gt; t.MyTable2);
  </code></pre>
  
  <p>And changing my tables to this: (The FK to the MyTable2 and removed from the view)</p>
  
  <hr>
  
  <p><strong>MyTable1</strong></p>
  
  <p>+id</p>
  
  <hr>
  
  <p><strong>MyTable2</strong></p>
  
  <p>+id
  +myTable1</p>
  
  <hr>
  
  <p><strong>MyView1</strong></p>
  
  <p>+id</p>
  
  <hr>
  
  <p>Which in the end is better because this way i have less Null values in my model.</p>