EF Core Composite Key, one foreign, one auto incrementing
<p>I have this entity:</p>
<pre><code>public class PlayerScoreHistory
{
    public int Id { get; set; }

    public int PlayerScoreId { get; set; }

    public DateTime ScoreWhen { get; set; }
}
</code></pre>
<p>I need to make a composite key out of both of those <code>Id</code> fields. <code>PlayerScoreId</code> needs to be a foreign key to <code>PlayerScore.Id</code> . <code>Id</code> needs to be an auto incrementing id.</p>
<p>So, I got as far as:</p>
<pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity&lt;PlayerScoreHistory&gt;()
        .HasKey(x =&gt; new { x.Id, x.PlayerScoreId });
}
</code></pre>
<p>This gives me the composite key. I did <code>Add-Migration Initial</code> to give me my initial migration.</p>
<p>To get the Foreign Key, I simply added the line in the <code>constraints</code> parameter:</p>
<pre><code> migrationBuilder.CreateTable(
    name: &quot;PlayerScoreHistories&quot;,
    columns: table =&gt; new
        {
            Id = table.Column&lt;int&gt;(nullable: false),
            PlayerScoreId = table.Column&lt;int&gt;(nullable: false),
            ScoreWhen = table.Column&lt;DateTime&gt;(nullable: false)
        },
    constraints: table =&gt;
        {
            table.PrimaryKey(&quot;PK_PlayerScoreHistories&quot;, x =&gt; new { x.Id, x.PlayerScoreId });
            table.ForeignKey(&quot;FK_PlayerScoreId&quot;, arg =&gt; new {  arg.PlayerScoreId}, &quot;PlayerScores&quot;, &quot;Id&quot;);
        });
</code></pre>
<p>So two questions:</p>
<ol>
<li>How can I get the foreign key creation in the <code>OnModelCreating</code> method?</li>
<li>How can I make the <code>Id</code> column a Database Generated field and make sure EF Core doesn't try and set a value?</li>
</ol>
<p>I'm not exactly sure what options are open to me, seeing as EF Core is extremely new...</p>
<p>The two errors I get:</p>
<h2>1.</h2>
<p>When I add this line to the <code>Id</code> <code>column</code> parameter configuration:</p>
<pre><code>Annotation(&quot;SqlServer:ValueGenerationStrategy&quot;, SqlServerValueGenerationStrategy.IdentityColumn)
</code></pre>
<p>I get</p>
<blockquote>
<p>SQL Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF [duplicate]</p>
</blockquote>
<h2>2.</h2>
<p>When I remove the line and then try and add an entity, I get:</p>
<blockquote>
<p>Can't insert null into column <code>Id</code></p>
</blockquote>
<hr />
<p>Clearly I'm in between somewhere....</p>
<hr />
<h2>Edit So Far</h2>
<p>I decided to remove the <code>Id</code> column and just use <code>PlayerScoreId</code> and <code>ScoreWhen</code> as the composite keys....</p>
<p>But, one question I still have is how to make <code>OnModelCreating</code> identity <code>PlayerScoreId</code> as a foreign key - without having navigation properties.....</p>