使用存储库和TPT时避免重复

时间:2016-12-21 22:02:31

标签: c# asp.net-mvc

我在我的用户相关表的新项目中使用EF和TPT,但我不断重复自己,我不知道如何解决问题。 基本上,我有4个表:用户(所有),来宾,管理员和注册用户。然后我为每张桌子准备了一个模型。

因为,我正在遵循存储库模式,我创建了:

  • IUserRepository
  • RegisteredUserRepository(实现界面)
  • GuestUsersRepository(实现界面)
  • AdminUsersRepository(实现界面)

事情是.. 我只想要一个实现接口的UserRepository ,因为我的存储库中有很多基本相同的方法。 但是,每当我尝试使用单个仓库时,我都会遇到问题,即由于 不同类型的用户具有不同的属性 (例如:已注册和管理员)用户有电子邮件地址,用户名和密码,而访客用户没有)。 因此,我无法使用通用方法

有什么建议吗?提前谢谢!

IUserRepository:

 interface IUserRepository<T> where T: User  {

        T Find(Expression<Func<T, bool>> predicate);
        T GetById(int id);
        T GetByEmail(string email);
        T GetByUsername(string username);
        bool Login(string email, string password);
        bool Add(T user);
        void Update(T user);
        void Delete(T user);

RegisteredUserRepository:

 public class RegisteredUserRepository : IUserRepository<RegisteredUser> {
        // context here

        public RegisteredUser Find(Expression<Func<RegisteredUser, bool>> predicate) {
            return _db.Users.OfType<RegisteredUser>().SingleOrDefault(predicate);
        }

        public RegisteredUser GetById(int id) {
            return this.Find(u => u.Id == id);
        }

        // HERE lies my problem: I can't make all of these methods generic because there are some properties (eg: email) that registered and admin users have and that guests don't
        public RegisteredUser GetByEmail(string email) {
            return this.Find(u => u.Email == email); 
        }

        // same thing here...   
        public bool Login(string usernameOrEmail, string password) {
            var user = this.Find(u => u.Email == usernameOrEmail || a.Username == usernameOrEmail);
            return BCrypt.Net.BCrypt.Verify(password, user.Password);
       }

GuestUserRepository:

  public class GuestUserRepository : IUserRepository<GuestUser> {
        // context here...

    public GuestUser Find(Expression<Func<GuestUser, bool>> predicate) {
         return db.Users.OfType<GuestUser>().SingleOrDefault(predicate);
    }

    public GuestUser GetById(int id) {
        return this.Find(g => g.Id == id);
    }

    // etc, etc

0 个答案:

没有答案
相关问题