簡體   English   中英

如何實現通用的 GetById(),其中 Id 可以是各種類型

[英]How to implement generic GetById() where Id can be of various types

我正在嘗試實現一個通用的GetById(T id)方法,該方法將滿足可能具有不同 ID 類型的類型。 在我的示例中,我有一個實體,其 ID 類型為int ,類型為string

但是,我不斷收到錯誤消息,我不知道為什么:

類型“int”必須是引用類型,以便在方法 IEntity 的泛型類型中將其用作參數“TId”

實體接口:

為了迎合我的域模型,這些模型可以具有intstring類型的 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...
    }

您應該從Repository類中刪除對 TId 的約束

public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : class, IEntity<TId>
{
    public virtual TEntity GetById(TId id)
    {
        return context.Set<TEntity>().Find(id);
    }
}
public interface IEntity<TId> where TId : class
{
    TId Id { get; set; }
}

where TId : class約束要求每個實現都有一個從 object 派生的 Id,這對於像 int 這樣的值類型不正確。

這就是錯誤消息告訴您的內容: The type 'int' must be a reference type in order to use it as parameter 'TId' in the generic type of method IEntity

只需刪除約束where TId : class from IEntity<TId>

對於你的問題:
我正在嘗試實現一個通用的 GetById(T id) 方法,該方法將滿足可能具有不同 ID 類型的類型。 在我的示例中,我有一個實體,其 ID 為 int 類型,其中一個為 string 類型。

    public virtual TEntity GetById<TId>(TId id)
    {
        return context.Set<TEntity>().SingleOrDefault(x => x.Id == id);
    }

對於泛型參數,只需創建一個像上面一樣的泛型方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM