異なるIDタイプの可能性があるタイプに対応する一般的なGetById(T id)
メソッドを実装しようとしています。私の例では、IDがint
、タイプがstring
のエンティティを持っています。一般的なGetById()の実装方法IDはさまざまな種類があります。
しかし、私はエラーを取得しておくと、私はその理由は考えていません:
型「intは」メソッドIEntityのジェネリック型のパラメータ「TID」としてそれを使用するために、参照型でなければなりませんが
エンティティインタフェース:
タイプint
またはstring
のIDを持つことができ、私のドメインモデルに対応するために。
public interface IEntity<TId> where TId : class
{
TId Id { get; set; }
}
エンティティの実装:
public class EntityOne : IEntity<int>
{
public int Id { get; set; }
// Other model properties...
}
public class EntityTwo : IEntity<string>
{
public string Id { get; set; }
// Other model properties...
}
ジェネリックリポジトリインタフェース:
public interface IRepository<TEntity, TId> where TEntity : class, IEntity<TId>
{
TEntity GetById(TId id);
}
一般的なリポジトリの実装:
public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : class, IEntity<TId>
where TId : class
{
// Context setup...
public virtual TEntity GetById(TId id)
{
return context.Set<TEntity>().SingleOrDefault(x => x.Id == id);
}
}
リポジトリの実装:
public class EntityOneRepository : Repository<EntityOne, int>
{
// Initialise...
}
public class EntityTwoRepository : Repository<EntityTwo, string>
{
// Initialise...
}
からcontraintを削除しますか?これは 'int'では機能しません(エラーメッセージはそれをかなり明確にします)。 'class'は、ジェネリック制約の「参照型」を意味します。 –