How to implement generic GetById() where Id can be of various types
<p>I am trying to implement a generic <code>GetById(T id)</code> method which will cater for types which may have differing ID types. In my example, I have an entity which has an ID of type <code>int</code>, and one of type <code>string</code>.</p>

<p>However, I keep getting an error and I have no idea why:</p>

<p><em>The type 'int' must be a reference type in order to use it as parameter 'TId' in the generic type of method IEntity</em></p>

<p><strong>Entity Interface:</strong></p>

<p>To cater for my domain models which can have Id's of type <code>int</code> or <code>string</code>.</p>

<pre><code>public interface IEntity&lt;TId&gt; where TId : class
{
    TId Id { get; set; }
}
</code></pre>

<p><strong>Entity Implementations:</strong></p>

<pre><code>public class EntityOne : IEntity&lt;int&gt;
{
    public int Id { get; set; }

    // Other model properties...
}

public class EntityTwo : IEntity&lt;string&gt;
{
    public string Id { get; set; }

    // Other model properties...
}
</code></pre>

<p><strong>Generic Repository Interface:</strong></p>

<pre><code>public interface IRepository&lt;TEntity, TId&gt; where TEntity : class, IEntity&lt;TId&gt;
{
    TEntity GetById(TId id);
}
</code></pre>

<p><strong>Generic Repository Implementation:</strong></p>

<pre><code>public abstract class Repository&lt;TEntity, TId&gt; : IRepository&lt;TEntity, TId&gt;
    where TEntity : class, IEntity&lt;TId&gt;
    where TId : class
{
    // Context setup...

    public virtual TEntity GetById(TId id)
    {
        return context.Set&lt;TEntity&gt;().SingleOrDefault(x =&gt; x.Id == id);
    }
}
</code></pre>

<p><strong>Repository Implementations:</strong></p>

<pre><code> public class EntityOneRepository : Repository&lt;EntityOne, int&gt;
    {
        // Initialise...
    }

    public class EntityTwoRepository : Repository&lt;EntityTwo, string&gt;
    {
        // Initialise...
    }
</code></pre>