1

我尝试了以下存储库模式实现

interface IRepository<T>
{
    IQueryable<T> All { get; }
    T Find(object id);
    void Insert(T model); 
}

然后我在下面定义了 IAdminRepository

interface IAdminRepository : IRpository<Role>, IRepository<User>
{
}

public class AdminRepository:IAdminRepository
{
    IQueryable<User> IRepository<User>.All
    {
        get { throw new NotImplementedException(); }
    }

    User IRepository<User>.Find(object id)
    {
        throw new NotImplementedException();
    }

    void IRepository<User>.Insert(User model)
    {
        throw new NotImplementedException();
    }

    IQueryable<Role> IRepository<Role>.All
    {
        get { throw new NotImplementedException(); }
    }

    Role IRepository<Role>.Find(object id)
    {
        throw new NotImplementedException();
    }

    void IRepository<Role>.Insert(Role model)
    {
        throw new NotImplementedException();
    }
}

在我的业务层中,我使用基于接口的调用。

public interface IAdminService
{
    bool CreateUser(User user);        
    List<User> GetAllUsers();
}

public class AdminService : IAdminService
{
    private readonly IAdminRepository AdminRepository;

    public AdminService(IAdminRepository _adminRepository)
    {
        AdminRepository = _adminRepository;
    }

    public bool CreateUser(User user)
    {
        AdminRepository.Insert(user);
        return true;
    }

    public List<User> GetAllUsers()
    {
        return AdminRepository.All; // Here is error 
    }
}

错误:IRepository.All 和 IRepository.All 之间存在歧义。

如何解决这个问题?我以这种方式使用存储库模式的方法有什么问题?

4

2 回答 2

1

消除调用歧义的一种简单方法是创建别名方法:

public class AdminRepository : IAdminRepository {

  public IQueryable<User> AllUsers {
    get { throw new NotImplementedException(); }
  }

  public IQueryable<Role> AllRoles {
    get { throw new NotImplementedException(); }
  }

  IQueryable<User> IRepository<User>.All {
    get { return AllUsers; }
  }

  IQueryable<Role> IRepository<Role>.All {
    get { return AllRoles; }
  }

  ...
}
于 2013-03-16T15:52:04.537 回答
1

我猜这条线

return AdminRepository.All; // Here is error 

应该

return ((IRepository<User>)AdminRepository).All.ToList();

.All您可能注意到,如果不显式编写您正在实现的接口,您将无法声明。这是因为,对于一个给定的类,两个同名的属性不能有不同的返回类型。

调用时也是一样。您必须准确说明您正在调用哪个属性。这是通过将对象转换为所需的接口来完成的。

无论如何,您似乎最终会为您的所有实体类型实现存储库。IRepository<T>对于可以从同一机制中检索的实体类型,您应该只实现一次。

如果您希望您的存储库仅适用于某些类,例如,您可以使用接口标记这些类。比方说IEntity

public interface IEntity
{
}

然后

public interface IRepository<T> where T:IEntity
{
    IQueryable<T> All { get; }
    T Find(object id);
    void Insert(T model);
}

您甚至可以拥有仅适用于您标记为 db 实体的实体的 db 存储库,如下所示:

public interface IDbEntity: IEntity
{
}


public class DbRepository<T> : IRepository<T> where T:IDbEntity
{
    public IQueryable<T> All { get; private set; }
    public T Find(object id)
    {
        throw new NotImplementedException();
    }

    public void Insert(T model)
    {
        throw new NotImplementedException();
    }
}
于 2013-03-15T10:01:58.337 回答