2011-01-13 5 views
1

Inspiriert von http://huyrua.wordpress.com/2010/08/25/specification-pattern-in-entity-framework-4-revisited habe ich beschlossen, alle nichttrivialen Abfragen über Spezifikationen zu schreiben. Aber у hat ein Problem, dass ich weiß nicht, wie eine Spezifikation in wenigen Funktionen zu nutzen:Spezifikationsmuster für das Repository?

public bool CheckAccountEmailExist(string email) 
{ 
    var emailExistSpec = new Specification(a => a.Email.ToUpper() == email.ToUpper()); 
    return _accountRepository.GetBy(emailExistSpec).Any(); 
} 

public bool CheckAccountEmailExist(string email, Guid exceptAccountId) 
{ 
    var emailExistSpec = new Specification(a => a.Email.ToUpper() == email.ToUpper()); 
    var exceptAccountSpec = new Specification(a => a.Id != exceptAccountId); 
    return _accountRepository.GetBy(emailExistSpec.And(exceptAccountSpec)).Any(); 
} 

Ich möchte ein extrahieren Spezifikation“=> a.Email.ToUpper() == email.ToUpper() "Um es in beiden Funktionen zu verwenden, aber ich sollte es mit" email "(Funktionsparameter) parametrisieren. Wie kann ich das machen?

Antwort

3

Aus irgendeinem Grund, den ich nicht die Seite anzeigen können, die Sie verknüpfen, aber ich glaube, dass es so etwas wie dies gehen würde:

class EmailSpecification : Specification { 
    public EmailSpecification(string email) : 
     base(a => a.Email.ToUpper() == email.ToUpper()) 
    { 
    } 
} 

Dann:

public bool CheckAccountEmailExist(string email) { 
    var emailExistSpec = new EmailSpecification(email); 
    return _accountRepository.GetBy(emailExistSpec).Any(); 
} 
3

denke ich, das Problem liegt in der Tatsache, dass Sie eine generische Specification Klasse verwenden, die einen Lambda-Ausdruck in seinem Konstruktor verwendet. Der Zweck einer Spezifikation ist meiner Meinung nach, eine Einschränkung für ein Domain-Objekt anzugeben. Deshalb denke ich, dass Sie Ihre Specification Klasse abstrahieren sollten, und erben Sie davon in einer EmailExistsSpecification Klasse und einer AccountIdIsNotEqualSpecification Klasse. Es könnte in etwa so aussehen:

public class EmailExistsSpecification : Specification<Account> 
{ 
    public EmailExistsSpecification(string email) 
     : base(a => a.Email.ToUpper() == email.ToUpper()) 
    { 
    } 
} 

Ich denke, dieser Ansatz ist mehr Absicht enthüllt als mit einer generischen Spezifikation Klasse.