2

我目前有这门课来弥补我的通用存储库

public abstract class RepositoryBase<T> where T : class
{
    private readonly ISession session;

    public RepositoryBase(ISession session)
    {
        this.session = session;
        this.session.FlushMode = FlushMode.Auto;
    }

    public void Start()
    {
        this.session.BeginTransaction();
    }

    public bool Add(T entity)
    {
        this.session.Save(entity);
        return true;
    }

    public bool AddAll(IEnumerable<T> items)
    {
        foreach (T item in items)
        {
            this.session.Save(item);
        }
        return true;
    }

    public bool Update(T entity)
    {
        this.session.Flush();
        this.session.Update(entity);
        return true;
    }

    public bool Delete(T entity)
    {
        this.session.Delete(entity);
        return true;
    }

    public bool DeleteAll(IEnumerable<T> entities)
    {
        foreach (T entity in entities)
        {
            this.Delete(entity);
        }
        return true;
    }

    public T GetById(int id)
    {
        return this.session.Get<T>(id);
    }

    public T GetById(string id)
    {
        return this.session.Get<T>(id);
    }

    public T GetById(long id)
    {
        return this.session.Get<T>(id);
    }

    public T GetById(Guid id)
    {
        return this.session.Get<T>(id);
    }

    public IQueryable<T> GetAll()
    {
        return this.session.Query<T>();
    }

    public T Get(Expression<System.Func<T, bool>> expression)
    {
        return GetMany(expression).SingleOrDefault();
    }

    public IQueryable<T> GetMany(Expression<System.Func<T, bool>> expression)
    {
        return GetAll().Where(expression).AsQueryable();
    }
}

当我调用带有字符串参数的 GetById 方法时,我遇到一个异常错误,指出 GetById 期望类型 Guid 而不是字符串。如何设计此方法以接受字符串参数?

4

1 回答 1

4

您可以设计您的类,为 id 类型添加另一个通用参数:

public abstract class Repository<T, TId>
{
    public T Get(TId id)
    {
    }
}

看看这个https://github.com/sharparchitecture/sharp-architecture/wiki

于 2013-09-07T21:22:54.253 回答